1

In the following code sample, matcher.matches() and String.matches do not return the same result and I don't understand why :

    String MIDDLESIGN = "[(\\/)"+"|"+"(\\*)"+"|"+"(\\++)"+"|"+"(\\-+)]";
    String x = "1 +++ 2 * 3 -- 4";
    System.out.println("1 +++ 2 * 3 -- 4".matches("(\\d+\\s+"+MIDDLESIGN+"*"+"\\s+\\d*)+")); //true

    Pattern pattern = Pattern.compile((\\d+\\s+"+MIDDLESIGN+"*"+"\\s+\\d*)+");
    Matcher matcher = pattern.matcher(x);

    System.out.println(matcher.matches()); //false

Any idea why this difference ?

momodjib
  • 183
  • 8
  • 2
    Does this answer your question? [What's the difference between String.matches and Matcher.matches?](https://stackoverflow.com/questions/2469244/whats-the-difference-between-string-matches-and-matcher-matches) – Optional Dec 26 '19 at 06:34
  • This is already addressed [here](https://stackoverflow.com/questions/2469244/whats-the-difference-between-string-matches-and-matcher-matches) – Seshidhar G Dec 26 '19 at 06:36
  • Look at this answer to understand why both returns the same result: https://stackoverflow.com/a/2469287/8112679 – Harshvardhan Joshi Dec 26 '19 at 06:42
  • @momodjib What is value of MIDDLESIGN?? – Sumit Singh Dec 26 '19 at 06:46
  • @HarshvardhanJoshi, in my case I get different results from both so it won't help me – momodjib Dec 26 '19 at 06:46
  • @SumitSingh we have the same MIDDLESIGN in both case so it should not matter but I edited the post to include it. – momodjib Dec 26 '19 at 06:49
  • *FYI:* When removing Java escapes and string concatenations, the `MIDDLESIGN` regex is `[(\/)|(\*)|(\++)|(\-+)]` which is a single character class that will match exactly *one* of the following characters: `( ) + - * / |`. The rest are just unnecessary escapes and redundant duplicates. You seem to expect it to mean something else, so reevaluate what you're trying to do. – Andreas Dec 26 '19 at 07:12

1 Answers1

1

Looks like issue in your code:

Its working fine: result

String MIDDLESIGN = "[(\\/)"+"|"+"(\\*)"+"|"+"(\\++)"+"|"+"(\\-+)]";
String x = "1 +++ 2 * 3 -- 4";
System.out.println("1 +++ 2 * 3 -- 4".matches("(\\d+\\s+" + MIDDLESIGN + "*" + "\\s+\\d*)+")); // true

Pattern pattern = Pattern.compile("(\\d+\\s+" + MIDDLESIGN + "*" + "\\s+\\d*)+");
Matcher matcher = pattern.matcher(x);
System.out.println(matcher.matches()); // true

From you code: Pattern.compile((\d+\s+"+MIDDLESIGN+""+"\s+\d)+");

there is missing " in it. replace it with below code:

Pattern pattern = Pattern.compile("(\\d+\\s+" + MIDDLESIGN + "*" + "\\s+\\d*)+");
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89