1

I only want Strings with a very specific format to be allowed in my methods. The format is "Intx^Int". Here are some concrete examples:

  • "5x^2"
  • "-21x^5"
  • "14x^-12"

I tried the following code, but it doesn't seem to work correctly:

import java.util.regex.Pattern;

Pattern p = Pattern.compile("\\dx^\\d");
System.out.println(p.matcher("14x^-12").matches());

Nova
  • 588
  • 4
  • 16
  • 1
    Because you only match a single digit without any sign in front and do not escape `^`. `"-?\\d+x\\^-?\\d+"` can work for you. – Wiktor Stribiżew Oct 19 '21 at 17:01
  • That worked! If you throw that in an answer and quickly explain the -? syntax (I'm unfamiliar), I'll give you the checkmark! – Nova Oct 19 '21 at 17:04
  • 1
    Another approach: split the string on "x^" and verify that you get two substrings and that you can convert each of them to an integer. If everything goes fine, then the original string was valid. – Nir H. Oct 19 '21 at 17:05
  • 1
    `-?` means that a literal `-` character can be there, but it doesn't have to be (`?` means it's optional). Wiktor has added it so that your negative numbers still match. – Charlie Armstrong Oct 19 '21 at 17:10

1 Answers1

1

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?.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563