You only match a single digit (not whole numbers) without any sign in front (it seems you want to match optional -
chars in front of the numbers). You also failed to escape the ^
char that is a special regex metacharacter denoting the start of a string (or line if Pattern.MULTILINE
option is used).
You can use
Pattern p = Pattern.compile("-?\\d+x\\^-?\\d+");
System.out.println(p.matcher("14x^-12").matches());
The pattern matches
-?
- an optional -
\d+
- one or more digits
x
- an x
-\^
- a ^
char
-?
- an optional -
\d+
- one or more digits
To support numbers with fractions, you might further tweak the regex:
Pattern p = Pattern.compile("-?\\d+(?:\\.\\d+)?x\\^-?\\d+(?:\\.\\d+)?");
Pattern p = Pattern.compile("-?\\d*\\.?\\d+x\\^-?\\d*\\.?\\d+");
Also, see Parsing scientific notation sensibly?.