模式匹配如何使用java查找行中的给定字符串
我想在一条线上找到一个给定的刺。为此,我编写了代码。我使用Pattern类来查找给定字符串在一行中是否可用。它给出的是行,那些不是给定的字符串。我想要那些有给定字符串的行。请查一下我的密码
代码:
public class StringMatch {
public static void main(String args[]) throws FileNotFoundException, IOException{
String text="dsfhgs the dgfre fh" +
"hjfgeh fhg hghjr" +
"fhvhjf the vgh fhjghf" +
"fbvhjfd fhvfg fjvhf" +
"the hfdvhjf vhf fhdvjfd" +
"hfvbhd thehjdvhj hdfvhdf";
String pattern = ".*?\\the\\b.*?";
String f="C:\\TextFiles\\sample.txt";
String line;
BufferedReader br = new BufferedReader(new FileReader(f));
while(br.readLine()!=null) {
line=br.readLine();
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
} else {
System.out.println("NO MATCH");
}
}
}
}
# 1 楼答案
您可以通过以下方式进行尝试:
输出:
注意:
indexOf()
如果找到字符串,将返回第一个字符的位置,否则返回-1
。或者,也可以使用Regular Expressions
来搜索复杂字符串Using Regular Expressions :
输出:
# 2 楼答案
或者你应该使用String Contains
然后返回true或false
如果你不在乎这个案子,你就不得不这么做
contains区分大小写
它不会做任何华丽的正则表达式,尽管只是一个简单的比较检查
编辑
# 3 楼答案
这里的问题是(与大多数其他语言不同)在java中,
matches()
必须匹配整个字符串才能为true,因此在模式的每一端添加".*"
因为输入中有换行符,所以还需要添加
(?s)
来打开DOTALL标志,这会导致点也匹配换行符:# 4 楼答案
只需使用以下简单模式即可!!!:
我希望这对你有帮助
# 5 楼答案
您必须使用以下
Pattern
和Matcher
类:# 6 楼答案
我下面的答案对你有用吗