gpt4 book ai didi

java - 正则表达式转义字符

转载 作者:搜寻专家 更新时间:2023-11-01 03:27:52 24 4
gpt4 key购买 nike

我必须将一大堆电子邮件和姓名分开,我必须用逗号分隔,但有些姓名中有逗号,所以我必须先处理它。幸运的是,名字在“引号”之间。

例如,目前我的正则表达式输出是这样的(编辑:它不会在我看到的论坛中显示电子邮件!):

"Talboom, Esther"

"Wolde, Jos van der"

"Debbie Derksen" <deberken@casema.nl>, corine <corine5@xs4all.nl>, "

最后一个出错了,因为名字没有逗号,所以它会继续,直到找到一个,这就是我想用来分隔的那个。所以我希望它一直查找直到找到“<”。我该怎么做?

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

String test = "\"Talboom, Esther\" <E.Talboom@wegener.nl>, \"Wolde, Jos van der\" <J.vdWolde@wegener.nl>, \"Debbie Derksen\" <deberken@casema.nl>, corine <corine5@xs4all.nl>, \"Markies Aart\" <A.Markies@wegenernieuwsmedia.nl>";

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

Matcher matcher = pattern.matcher(test);

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

编辑:更好的工作方式,因为并非所有人都有名字或引号:

String test = "\"Talboom, Esther\" <E.Talboom@wegener.nl>,     DRP - Wouter Haan <wouter@drp.eu>, \"Wolde, Jos van der\" <J.vdWolde@wegener.nl>,   \"Debbie Derksen\"  <deberken@casema.nl>,   corine  <corine5@xs4all.nl>, clankilllller@gmail.com, \"Markies Aart\" <A.Markies@wegenernieuwsmedia.nl>";

最佳答案

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

public static void main(String[] args) {
String test = "\"Talboom, Esther\" <E.Talboom@wegener.nl>, \"Wolde, Jos van der\" <J.vdWolde@wegener.nl>, \"Debbie Derksen\" <deberken@casema.nl>, corine <corine5@xs4all.nl>, \"Markies Aart\" <A.Markies@wegenernieuwsmedia.nl>";

// 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 = E.Talboom@wegener.nl
Wolde, Jos van der = J.vdWolde@wegener.nl
Debbie Derksen = corine5@xs4all.nl
Markies Aart = A.Markies@wegenernieuwsmedia.nl

关于java - 正则表达式转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8621100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com