0

i have made this code and i don't know what is the problem with it, why the output print " f "??? even that the string contains the specified characters in the regex

String s="x^2+x-20"; 
Pattern pattern = 
Pattern.compile("([+-][0-9]*)(([a-z A-Z])\\^2)"); //regex

Matcher matcher = pattern.matcher(s);

if(matcher.matches()){
   System.out.println("t");
} else {
   System.out.println("f");}
M A
  • 71,713
  • 13
  • 134
  • 174
odaaa
  • 23
  • 3

1 Answers1

0

Your regex makes [+-] not an optional match but rather required. Use the following:

"([+-]?[0-9]*)(([a-z A-Z])\\^2)" // java syntax

Or as a regex without any java escaping:

([+-]?[0-9]?)(([a-z A-Z])\^2)

Also use Matcher.find rather than Matcher.match to find matches that are not the entire string.

nanofarad
  • 40,330
  • 4
  • 86
  • 117