简体   繁体   English

Java正则表达式模式匹配始于

[英]Java regex pattern matching start with

I have a file containing lots of lines. 我有一个包含很多行的文件。 I want to find a specific line starting with "msql". 我想找到以“ msql”开头的特定行。

I have tried many regex combinations but not get any idea. 我已经尝试了许多正则表达式组合,但没有任何想法。

Pattern pattern = Pattern.compile("^msql");
Matcher matcher = pattern.matcher(s);

or 要么

s.matches("^(msql).*$")  or s.matches("^msql")

please suggest correct regex for finding a line start with "msql". 请建议正确的正则表达式来查找以“ msql”开头的行。

EDIT:- 编辑:-

i have file data like this:- 我有这样的文件数据:

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

and my code. 和我的代码。

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();
}

still am not able to find line. 仍然找不到线。

I think you are reading only first line and hence no match found. 我认为您只读取第一行,因此找不到匹配项。

  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);
            }
        }
    } 

and output is Match found: msqlpdmm81dd 0 0 25 25 25 Match found: msqlpdmm81dd 0 0 25 25 25输出Match found: msqlpdmm81dd 0 0 25 25 25

Your regex for matching the content is correct. 您用于内容匹配的正则表达式是正确的。 I do not know why are you facing problem. 我不知道你为什么要面对问题。 I have tried your program and it is working. 我已经尝试过您的程序,它正在运行。
I m adding the code with regex below. 我在下面用正则表达式添加代码。

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");
            }
        }

You can also check the condition using 您也可以使用

if (s.startsWith("msql"))

This is also working fine. 这也很好。
I have created an text file in my local and saved your data in it. 我在本地创建了一个文本文件,并将您的数据保存在其中。 And I m getting the following output. 我得到以下输出。

didnt matched
didnt matched
didnt matched
msqlpdmm81dd 0 0 25 25 25

I think this should work. 我认为这应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM