How write regex for matches String and BigInteger in java?

Tags:



I tried to use this site https://www.freeformatter.com/java-regex-tester.html#ad-output. But I didn’t succeed.

My Java Regular Expression :

(.*)\w+=[0-9][0-9]*$(.*)

Entry to test against :

a = 800000000000000000000000

My code needs to give true for data.matches("(.*)\w+=[0-9][0-9]*$(.*)") of a = 800000000000000000000000.

Answer

Do it as follows:

public class Main {
    public static void main(String[] args) {
        String[] testStrs = { "a = 800000000000000000000000", "a = ABC800000000000000000000000",
                "a = 800000000000000000000000ABC", "a = 12.45", "a = 800000000000ABC000000000000", "a = ABC",
                "a = 900000000000000000000000", "a = -800000000000000000000000", "a = -900000000000000000000000" };
        for (String str : testStrs) {
            System.out.println(
                    str + " -> " + (str.matches("[A-Za-z]\s+=\s+[-]?\d+") ? " matches." : " does not match."));
        }
    }
}

Output:

a = 800000000000000000000000 ->  matches.
a = ABC800000000000000000000000 ->  does not match.
a = 800000000000000000000000ABC ->  does not match.
a = 12.45 ->  does not match.
a = 800000000000ABC000000000000 ->  does not match.
a = ABC ->  does not match.
a = 900000000000000000000000 ->  matches.
a = -800000000000000000000000 ->  matches.
a = -900000000000000000000000 ->  matches.

Explanation:

  1. [A-Za-z] is for alphabets
  2. \s+ is for space(s)
  3. [-]? is for optional -
  4. \d+ is for digits


Source: stackoverflow