Akash S Akash S - 1 month ago 6
Java Question

How do I exclude certain characters from pattern matching in regex?

I'm trying to implement my own version of atoi and so I want to check if my string contains non-numeric characters and handle the error, but I also also want the search pattern to exclude the + and - symbols (i.e + and - at the start of the string only are valid symbols). I currently have

word.matches("^[+=][a-zA-Z]+")
, but am not sure how to change it accordingly to fit my needs.
Ex: 20e48 is invalid, 204-8 is invalid, +2048 is valid and so is -2048

Answer

Here you go:

public static void main(String[] args) {
    String pattern = "^[+-]?[0-9]+$";
    System.out.println("20e48".matches(pattern));
    System.out.println("204-8".matches(pattern));
    System.out.println("+2048".matches(pattern));
    System.out.println("-2048".matches(pattern));
    System.out.println("2048".matches(pattern));
}

It prints:

false
false
true
true
true

Explanation:

^ => Starts
[+-] => Either plus or minus sign
? => Zero or one occurance
[0-9] => Any number
+ => One or more occurance
$ => End

If any string does not match this pattern, it is not a valid input.