简体   繁体   中英

Java Regex find() method not returning proper value

I've created a regex pattern in Java and, apparently, the matcher class find it into the string, but it is not returning the proper value.

If you see this image , Eclipse is giving me a 'true' value when I execute m.find() method, but it's not assigning it properly to isMatch variable.

Same occurs when I write " if (m.find()) , it doesn't go to the inner block.

Code Example:

{

    private final static String REGEX_PATTERN_FILE_GROUP = "(\\d{14}_\\d{9}_\\D{3}_\\d{11}_)";

    for (File file: fileList) {
        Pattern p = Pattern.compile(REGEX_PATTERN_FILE_GROUP);  
        Matcher m = p.matcher(file.getName());              
        if (m.find())
        {   
           .... More code ...
        }

}

Example of file.getName() value: "1.0- 20190409095211_200522007_CNA_20180000959_1_xxxxx.pdf"

Apparently, m.find() is 'true' (so as Eclipse is showing me), but it never goes into inner if block, neither if I try to assign to another boolean value.

Tested in https://regex101.com/ and it get value.

My Java version is "1.8.0_181" 64-Bit server.

I'm newbie in StackOverflow, Java and Eclipse.

Looking at your screenshot, where it shows m.find() as true and the same value assigned to isMatch variable to be false , meaning both are not in sync, and the only reason I can think of is, as you are in debug mode and since you have them in expression window, m.find() seems to be getting executed multiple times, where the first time value of m.find() must have been true, but as it got executed again, next time it didn't match the data and m.find()'s value became false and that ultimately got assigned to isMatch variable.

Try getting rid of debug mode and just run the code and the variable isMatch 's value should be in sync and should be as expected. Or you can even just turn off the expressions window while debugging your code, and debugging should give you correct values as expected. Make sure you don't re-evaluate m.find() else your program will give you unexpected results.

Also, never access .group() methods unless value returned by m.find() or m.matches() is true

For me, your code works fine like expected and prints true .

String REGEX_PATTERN_FILE_GROUP = "(\\d{14}_\\d{9}_\\D{3}_\\d{11}_)";

String s = "1.0- 20190409095211_200522007_CNA_20180000959_1_xxxxx.pdf";
Pattern p = Pattern.compile(REGEX_PATTERN_FILE_GROUP);
Matcher m = p.matcher(s);
boolean isMatch = m.find();
System.out.println("isMatch: " + isMatch);
if (isMatch) {
    System.out.println(m.group());
}

Prints,

isMatch: true
20190409095211_200522007_CNA_20180000959_

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