vendredi 29 mai 2015

Different behavior of same regular expression in python and java

Firstly, my apologies as I don't know regular expressions that well.

I am using a regular expression to match a string. I tested it on python command line interface but when I ran it in Java, it produced a different result.

Python execution:

re.search("[0-9]*[\\.[0-9]+]?[^0-9]*D\\([M|W]\\)\\s*US", "9.5 D(M) US");

gives the result as:

<_sre.SRE_Match object; span=(0, 11), match='9.5 D(M) US'>

But the Java code

import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class RegexTest {
    private static final Pattern FALLBACK_MEN_SIZE_PATTERN = Pattern.compile("[0-9]*[\\.[0-9]+]?[^0-9]*D\\([M|W]\\)\\s*US");

    public static void main(String[] args) {
    String strTest = "9.5 D(M) US";
    Matcher matcher = FALLBACK_MEN_SIZE_PATTERN.matcher(strTest);
        if (matcher.find()) {
            System.out.println(matcher.group(0));
        }
    }
}

gives the output as:

5 D(M) US

I don't understand why it is behaving the different way.

Aucun commentaire:

Enregistrer un commentaire