2011-12-01 184 views
1

我有两个字符串看起来像这样的正则表达式匹配特定字符串的字符>

X-Antivirus-Mail-From: [email protected] via mail From: "Test UserAccount" <[email protected]> there is more information past this 

X-Antivirus-Mail-From: [email protected] via mail From: <[email protected]> there is more information past this 

我想创建一个正则表达式,将返回本作的第一个字符串

From: "Test UserAccount" <[email protected]> 

这第二串

From: <[email protected]> 

到目前为止,我的正则表达式图案看起来像这样

From: ["<].* 

但我希望它总是在字符>上结束。

任何帮助?谢谢!

回答

0

您可以使用此

From: (".*?")?<.*?> 
+0

我怎样才能把这个java吗? “性格给我的问题,如果我\”他们这样做鼻涕工作。 – medium

+0

Java倾向于自动添加锚点,因此您需要迎合这一点。 – npinti

0

这是一个很好的起点,但你需要的所有字符匹配,直到>所以将其更改为:

From: ["<][^>]*> 
0

这将工作(与你的两个测试RegExBuddy

.*<(.*)> 

这些匹配是在capture gr中返回的牛津大学出版社1.

RegexBuddy screen capture

0

这似乎工作:

mail (From: .*\s*<.*>) 

全面括号中的内容应该匹配为一组,这应该允许你提取你需要没有任何问题的文本。

编辑,既然你提到了使用Java:

你需要做一些事情,像这样:

^.*mail (From: .*\s*<.*>).*$ 

默认情况下的Java增加了锚的字符串,它可能使你更难匹配。

你可以看看this来自Oracle的Regex教程。

这个工作对我来说:

public static void main(String[] args) { 
     String str1 = "X-Antivirus-Mail-From: [email protected] via mail From: \"Test UserAccount\" <[email protected]> there is more information past this"; 
     String str2 = "X-Antivirus-Mail-From: [email protected] via mail From: <[email protected]> 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)); 
     } 

    } 

产量:

From: "Test UserAccount" <[email protected]> 
From: <[email protected]> 
0

试试这个:

\sFrom: ("[^"]+"\s)?(<[^>]+>) 

工作:http://regexr.com?2vbu3

更新:在Java中,你需要用\逃脱"像这样:

Pattern pat = Pattern.compile("\sFrom: (\"[^\"]+\"\s)?(<[^>]+>)"); 
+0

我怎么能得到这个编译在Java中使用“字符? – medium

+0

我已经更新了答案 –