Home > database >  How to check if a String with integers matches a specific pattern in Java?
How to check if a String with integers matches a specific pattern in Java?

Time:10-20

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());

CodePudding user response:

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

  • Related