gpt4 book ai didi

Java - 查找字符串中给定单词之前和之后的单词

转载 作者:行者123 更新时间:2023-12-02 13:03:59 25 4
gpt4 key购买 nike

假设我有一个字符串

String str = "This problem sucks and is hard"

我想得到“问题”之前和之后的单词,所以“这个”和“糟糕”。正则表达式是完成此任务的最佳方法(请记住,我是正则表达式的初学者),或者 Java 是否有某种库(即 StringUtils)可以为我完成此任务?

最佳答案

要查找给定单词之前和之后的单词,您可以使用以下正则表达式:

(\w+)\W+问题\W+(\w+)

捕获组是您要查找的单词。

在 Java 中,这将是:

Pattern p = Pattern.compile("(\\w+)\\W+problem\\W+(\\w+)");

Matcher m = p.matcher("This problem sucks and is hard");
if (m.find())
System.out.printf("'%s', '%s'", m.group(1), m.group(2));

输出

“这个”,“糟糕”

<小时/>

如果您想要完整的 Unicode 支持,请添加标志 UNICODE_CHARACTER_CLASS ,或内联为 (?U):

Pattern p = Pattern.compile("(?U)(\\w+)\\W+problema\\W+(\\w+)");

Matcher m = p.matcher("Questo problema è schifoso e dura");
if (m.find())
System.out.printf("'%s', '%s'", m.group(1), m.group(2));

输出

'Questo', 'è'

<小时/>

要查找多个匹配项,请使用 while 循环:

Pattern p = Pattern.compile("(?U)(\\w+)\\W+problems\\W+(\\w+)");

Matcher m = p.matcher("Big problems or small problems, they are all just problems, man!");
while (m.find())
System.out.printf("'%s', '%s'%n", m.group(1), m.group(2));

输出

'Big', 'or'
'small', 'they'
'just', 'man'
<小时/>

注意:使用 \W+ 允许符号出现在单词之间,例如“这里没有(!)问题”仍然会找到“否”“这里”

另请注意,数字被视为一个单词:“我在这里发现 1 个问题” 返回 “1”“此处”

关于Java - 查找字符串中给定单词之前和之后的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44211031/

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