2011-12-23 56 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]rp.eu>, \"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

+0

@fge多くの場合、* 2つのステップでこれらの処理を行う方が簡単です - 正規表現を読みやすくして、理解しやすくし、デバッグして維持する傾向があります – Bohemian

+0

また、 '.split()'は内部的に 'パターンとその提供された 'split()'メソッドを使うかもしれません; – fge

関連する問題