Nova
Nova

Reputation: 618

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

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:

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

Upvotes: 1

Views: 429

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

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

Upvotes: 1

Related Questions