简体   繁体   中英

Java regex pattern matching start with

I have a file containing lots of lines. I want to find a specific line starting with "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".

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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