简体   繁体   中英

Dynamic regex returns false while static regex returns true

For some reason Matcher.find() returns false when it should return true. Please check out the code below:

String[] strings = {
    "MSG://1/3/data1",
    "MSG://3/3/data3"
    "MSG://2/3/data2",
};

for (int i = 0; i < strings.length; i++) {
    for (int j = 0; j < strings.length; j++) {
        Pattern thePattern = Pattern.compile("^MSG://" + (j+1) + "/(.*)");
        //Pattern thePattern = Pattern.compile("^MSG://1/(.*)");
        Matcher theMatcher = thePattern.matcher(strings[j]);
        if (theMatcher.find()) {
            // Do something
        }
        else {
            // Do something else
        }
    }
}

In the above code, the uncommented thePattern = ... line will cause theMatcher.find() to always return false. But if you comment that line, and uncomment the line right under it, it works as one would expect it to. I'm thinking there's something going on in the conversion from int to String but I'm not a Java guru. Any help anyone can offer is greatly appreciated.

I am just guessing but if your intention is to parse your data in order MSG://1 , MSG://2 , MSG://3 then try changing strings[j] to strings[i] .

Or you can move creation of Pattern to outer loop and use it in inner one. This way you can still iterate over strings[j] and will not have to compile your pattern n^n times but just n times.

What I mean is

for (int i = 0; i < strings.length; i++) {
    Pattern thePattern = Pattern.compile("^MSG://" + (i+1) + "/(.*)");
    for (int j = 0; j < strings.length; j++) {

instead of

for (int i = 0; i < strings.length; i++) {
    for (int j = 0; j < strings.length; j++) {
        Pattern thePattern = Pattern.compile("^MSG://" + (j+1) + "/(.*)");

Result:

MSG://1/3/data1
MSG://2/3/data2
MSG://3/3/data3

OK, so I don't seem to have an issue when using Oracle JDK. But when I use OpenJDK, regardless of how I attempt to find the right message and extract the data, using indexOf() or contains() , I keep having failures. I even used a StringBuilder object to build a pattern and still get problems with matching.

So I'm going to chalk this up to a bug in OpenJDK and move on. Thanks for the advice on the Pattern object, @Pshemo. And thanks, everyone else, for your effort to help.

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