2011-12-23 99 views
4

我必须分开大量的电子邮件和名称,我必须用逗号分割,但有些名称中有逗号,所以我必须首先处理。幸运的是,名字介于“引号”之间。正则表达式在字符上转义

目前,我与我的正则表达式输出这样的,例如得到(编辑:它不会显示在论坛的邮件我见):

"Talboom, Esther" 

"Wolde, Jos van der" 

"Debbie Derksen" <[email protected]>, corine <[email protected]>, " 

最后一个出了问题导致了名字没有逗号,所以它继续下去,直到它找到一个,那是我想用来分开的那个。所以我希望它看起来直到找到'<'。 我该怎么做?

import java.util.regex.Pattern; 
import java.util.regex.Matcher; 

String test = "\"Talboom, Esther\" <[email protected]>,  \"Wolde, Jos van der\" <[email protected]>, \"Debbie Derksen\" <[email protected]>, corine <[email protected]>, \"Markies Aart\" <[email protected]>"; 

Pattern pattern = Pattern.compile("\".*?,.*?\""); 

Matcher matcher = pattern.matcher(test); 

boolean found = false; 
while (matcher.find()) { 
    System.out.println(matcher.group()); 
} 

编辑: 更好的线是与因为并不是所有的姓名或报价工作:

String test = "\"Talboom, Esther\" <[email protected]>,  DRP - Wouter Haan <[email protected]>, \"Wolde, Jos van der\" <[email protected]>, \"Debbie Derksen\" <[email protected]>, corine <[email protected]>, [email protected], \"Markies Aart\" <[email protected]>"; 

回答

2

我会用String.splitString.replaceAll简化代码。这避免了与Pattern一起工作的麻烦,并使代码简洁明了。
试试这个:

public static void main(String[] args) { 
    String test = "\"Talboom, Esther\" <[email protected]>,  \"Wolde, Jos van der\" <[email protected]>, \"Debbie Derksen\" <[email protected]>, corine <[email protected]>, \"Markies Aart\" <[email protected]>"; 

    // Split up into each person's details 
    String[] nameEmailPairs = test.split(",\\s*(?=\")"); 
    for (String nameEmailPair : nameEmailPairs) { 
     // Extract exactly the parts you need from the person's details 
     String name = nameEmailPair.replaceAll("\"([^\"]+)\".*", "$1"); 
     String email = nameEmailPair.replaceAll(".*<([^>]+).*", "$1"); 
     System.out.println(name + " = " + email); 
    } 
} 

的输出,显示它的实际工作:)

Talboom, Esther = [email protected] 
Wolde, Jos van der = [email protected] 
Debbie Derksen = [email protected] 
Markies Aart = [email protected] 
+0

我用的是相同的正则表达式比你之前 - 直到我看到它会失败的(法律)的名字,作为“我”,“。 – fge 2011-12-23 23:23:00

+0

@fge通常在* 2 *步骤中执行这些操作比较容易 - 它往往会保持正则表达式仍然可读,并且易于理解,调试和维护 – Bohemian 2011-12-23 23:25:41

+0

此外''.split()'将在内部使用'Pattern' ,不同之处在于它必须为每个'split()'调用创建一个新的 - 也可以使用一个Pattern及其提供的split()方法;) – fge 2011-12-23 23:25:47