我想查找括号中是否包含特定单词。如果找到那个词,我想得到那个特定括号旁边的单引号。
这是我的尝试:
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Test
{
public static void main(String[]args) throws IOException
{
String content ="(content1)'first' is the first to find then (content2)'second' and so on";
Matcher m = Pattern.compile("\\((.*?)\\)").matcher(content);
while(m.find())
{
if(m.group(1).contains("content2"))
{
System.out.println(m.group(1));
//it gives content2,want to get 'second'
}
}
}
}
问题:我在括号内找到了特定的词。现在,如何使用 java 获取特定括号后的单引号单词?
最佳答案
我们可以使用否定后视来处理您的要求,该后视断言 (content2)
出现在单引号中的单词之前:
(?<=\(content2\))'(.*?)'
然后,您真正想要的词应该在第一个捕获组中可用。这是一个工作脚本:
String content ="(content1)'first' is the first to find then
(content2)'second' and so on";
Matcher m = Pattern.compile("(?<=\\(content2\\))'(.*?)'").matcher(content);
while (m.find()) {
System.out.println(m.group(1));
}
Demo
关于java - 使用java查找特定括号后的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51472249/