gpt4 book ai didi

java - 尝试提取字符串中的模式

转载 作者:行者123 更新时间:2023-11-29 06:21:10 25 4
gpt4 key购买 nike

我试图在文本文件中提取给定的模式,但是,结果并不是我想要的 100%。

这是我的代码:

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

public class ParseText1 {

public static void main(String[] args) {

String content = "<p>Yada yada yada <code> foo ddd</code>yada yada ...\n"
+ "more here <2004-08-24> bar<Bob Joe> etc etc\n"
+ "more here again <2004-09-24> bar<Bob Joe> <Fred Kej> etc etc\n"
+ "more here again <2004-08-24> bar<Bob Joe><Fred Kej> etc etc\n"
+ "and still more <2004-08-21><2004-08-21> baz <John Doe> and now <code>the end</code> </p>\n";

Pattern p = Pattern
.compile("<[1234567890]{4}-[1234567890]{2}-[1234567890]{2}>.*?<[^%0-9/]*>",
Pattern.MULTILINE);

Matcher m = p.matcher(content);

// print all the matches that we find
while (m.find()) {

System.out.println(m.group());

}

}
}

我得到的输出是:

<2004-08-24> bar<Bob Joe>
<2004-09-24> bar<Bob Joe> <Fred Kej>
<2004-08-24> bar<Bob Joe><Fred Kej>
<2004-08-21><2004-08-21> baz <John Doe> and now <code>

我想要的输出是:

<2004-08-24> bar<Bob Joe>
<2004-08-24> bar<Bob Joe>
<2004-08-24> bar<Bob Joe>
<2004-08-21> baz <John Doe>

简而言之,必须提取“日期”、“文本(或空白)”和“名称”的序列。其他一切都应该避免。例如,标签“Fred Kej”之前没有任何“日期”标签,因此,它应该被标记为无效。

此外,作为附带问题,是否有一种方法可以存储或跟踪被跳过/拒绝的文本片段以及有效文本。

谢谢,布莱恩

最佳答案

此模式有效:"<\\d{4}-\\d{2}-\\d{2}>[^<]*<[^%\\d>]*>"

关于捕获不匹配的字符串,我觉得还是用 Matcher.start() 方便很多和 end()索引并从原始文本中提取子字符串,而不是摆弄已经相当复杂的模式。


String content = "<p>Yada yada yada <code> foo ddd</code>yada yada ...\n"
+ "more here <2004-08-24> bar<Bob Joe> etc etc\n"
+ "more here again <2004-09-24> bar<Bob Joe> <Fred Kej> etc etc\n"
+ "more here again <2004-08-24> bar<Bob Joe><Fred Kej> etc etc\n"
+ "and still more <2004-08-21><2004-08-21> baz <John Doe> and now <code>the end</code> </p>\n";

Pattern p = Pattern.compile(
"<\\d{4}-\\d{2}-\\d{2}>[^<]*<[^%\\d>]*>",
Pattern.MULTILINE
);

Matcher m = p.matcher(content);
int index = 0;
while (m.find()) {
System.out.println(content.substring(index, m.start()));
System.out.println("**MATCH START**" + m.group() + "**MATCH END**");
index = m.end();
}
System.out.println(content.substring(index));

这打印:

<p>Yada yada yada <code> foo ddd</code>yada yada ...
more here
**MATCH START**<2004-08-24> bar<Bob Joe>**MATCH END**
etc etc
more here again
**MATCH START**<2004-09-24> bar<Bob Joe>**MATCH END**
<Fred Kej> etc etc
more here again
**MATCH START**<2004-08-24> bar<Bob Joe>**MATCH END**
<Fred Kej> etc etc
and still more <2004-08-21>
**MATCH START**<2004-08-21> baz <John Doe>**MATCH END**
and now <code>the end</code> </p>

关于java - 尝试提取字符串中的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2981209/

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