Regex 正则表达式将特定字符串与字符匹配>;
我有两条像这样的线Regex 正则表达式将特定字符串与字符匹配>;,regex,Regex,我有两条像这样的线 X-Antivirus-Mail-From: firstemail@home.com via mail From: "Test UserAccount" <mygmail@gmail.com> there is more information past this X-Antivirus-Mail-From: secondemail@home.com via mail From: <mysecondgmail@gmail.com> there is
X-Antivirus-Mail-From: firstemail@home.com via mail From: "Test UserAccount" <mygmail@gmail.com> there is more information past this
X-Antivirus-Mail-From: secondemail@home.com via mail From: <mysecondgmail@gmail.com> there is more information past this
X-Antivirus-Mail-From:firstemail@home.com通过邮件:“Test UserAccount”有更多信息
X-Antivirus-Mail-From:secondemail@home.com通过邮件发件人:这里有更多信息
我正在尝试创建一个正则表达式,它将为第一个字符串返回这个值
From: "Test UserAccount" <mygmail@gmail.com>
From:“测试用户帐户”
这是第二个字符串
From: <mysecondgmail@gmail.com>
来自:
到目前为止,我的正则表达式模式是这样的
From: ["<].*
From:[”
有什么帮助吗?谢谢!你可以用这个
From: (".*?" )?<.*?>
From:(“*?”)?
这是一个很好的起点,但您需要匹配所有字符,直到
,因此将其更改为:
From: ["<][^>]*>
From:[“]*>
这将起作用(使用中的两行文本进行测试)
*
在捕获组1中返回匹配项
这似乎有效:
mail (From: .*\s*<.*>)
邮件(发件人:.*\s*)
圆括号中的内容应作为一个组进行匹配,这应允许您提取所需的文本,而不会出现任何问题
编辑,因为您提到了Java的使用:
您需要这样做:
^.*mail (From: .*\s*<.*>).*$
^.*邮件(发件人:.*\s*)*$
默认情况下,Java会在字符串中添加锚点,这可能会使匹配更加困难
您可以查看Oracle的正则表达式教程
这对我很有用:
public static void main(String[] args) {
String str1 = "X-Antivirus-Mail-From: firstemail@home.com via mail From: \"Test UserAccount\" <mygmail@gmail.com> there is more information past this";
String str2 = "X-Antivirus-Mail-From: secondemail@home.com via mail From: <mysecondgmail@gmail.com> there is more information past this ";
Pattern pat = Pattern.compile("^.*mail (From: .*\\s*<.*>).*$");
Matcher m1 = pat.matcher(str1);
if (m1.matches())
{
System.out.println(m1.group(1));
}
Matcher m2 = pat.matcher(str2);
if (m2.matches())
{
System.out.println(m2.group(1));
}
}
publicstaticvoidmain(字符串[]args){
String str1=“X-Antivirus-Mail-From:firstemail@home.com通过邮件发送至:\“Test UserAccount\”此处有更多信息;
String str2=“X-Antivirus-Mail-From:secondemail@home.com通过邮件发送:此处有更多信息”;
Pattern pat=Pattern.compile(“^.*邮件(发件人:.*\\s*).*$”;
匹配器m1=匹配器(str1);
if(m1.matches())
{
系统输出println(m1组(1));
}
匹配器m2=匹配器(str2);
if(m2.matches())
{
系统输出打印LN(m2组(1));
}
}
收益率:
From: "Test UserAccount" <mygmail@gmail.com>
From: <mysecondgmail@gmail.com>
From:“测试用户帐户”
发件人:
试试这个:
\sFrom: ("[^"]+"\s)?(<[^>]+>)
我怎样才能把它放到java中呢?这个“角色给了我问题,如果我给了我问题”,它就不起作用了。java似乎倾向于自动添加锚点……所以你也需要考虑到这一点。我怎样才能让它用“角色”在java中编译?
\sFrom: ("[^"]+"\s)?(<[^>]+>)
Pattern pat = Pattern.compile("\sFrom: (\"[^\"]+\"\s)?(<[^>]+>)");