[英]Java regex pattern matching start with
我有一个包含很多行的文件。 我想找到以“ msql”开头的特定行。
我已经尝试了许多正则表达式组合,但没有任何想法。
Pattern pattern = Pattern.compile("^msql");
Matcher matcher = pattern.matcher(s);
要么
s.matches("^(msql).*$") or s.matches("^msql")
请建议正确的正则表达式来查找以“ msql”开头的行。
编辑:-
我有这样的文件数据:
eventlogger 0 0 1 1 1 10
expireserv 0 0 1 1 1 10 "
partEOLserv 0 0 1 1 1 10
msqlpdmm81dd 0 0 25 25 25
和我的代码。
String s = br.readLine();
while (s != null) {
//Pattern pattern = Pattern.compile("^msql");
//("^(msql).*$")
//Matcher matcher = pattern.matcher(s);
System.out.println(s);
if (s.startsWith("msql")) {
System.out.println(s);
}
s = br.readLine();
}
仍然找不到线。
我认为您只读取第一行,因此找不到匹配项。
public static void main(String[] args) throws Exception {
File f = new File("example.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String temp = null;
while ((temp=br.readLine())!=null) {
if (temp.startsWith("msql")){
System.out.println("Match found: "+temp);
}
}
}
并Match found: msqlpdmm81dd 0 0 25 25 25
输出Match found: msqlpdmm81dd 0 0 25 25 25
您用于内容匹配的正则表达式是正确的。 我不知道你为什么要面对问题。 我已经尝试过您的程序,它正在运行。
我在下面用正则表达式添加代码。
BufferedReader br = new BufferedReader(new FileReader("<filepath\\filename.extension>"));
String s;
while ((s = br.readLine()) != null) {
if (s.matches("^(msql).*$")){
System.out.println(s);
} else {
System.out.println("didnt matched");
}
}
您也可以使用
if (s.startsWith("msql"))
这也很好。
我在本地创建了一个文本文件,并将您的数据保存在其中。 我得到以下输出。
didnt matched
didnt matched
didnt matched
msqlpdmm81dd 0 0 25 25 25
我认为这应该有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.