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 (ie + 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
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.
Try ^ followed by character you don't want to match in a square bracket. Eg [^k] will not match k character in given string.
This regex may work for you:
^[+-]{0,1}[0-9]*[^0-9]+[0-9]*$
It matches any string that (optionally) begins with + or -, followed by 0 or more numeric characters, followed by 1 or more non-numeric characters, followed by 0 or more numeric characters.
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.