简体   繁体   中英

How write regex for matches String and BigInteger in java?

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 .

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

expanding on the previous answer and the comment from atmin (i can't post comments anywhere yet), you could exclude leading zeroes as well with:

String regex = "0|(\\-?[1-9]\\d*)";
String stringToTest = "..."
boolean result = stringToTest.matches(regex);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM