sorry I don't know if you understand what I want to do and I am also not 100% sure if it can be done by regex, but maybe there is a better solution than the one I have in my mind.
I want to create a function which gets a string as a parameter and checks if there is an Integer in that string (this is the easy part) The function should return false, if there is an Integer, but with more than 2 digits or the digits are split.
Valid:
Invalid
So the easy part, regex for 1 or 2 digits is no big deal
[0-9]{1,2}
Another way, what I think is pretty bad code, is a loop through the whole String and count every int. As soon as I saw one and the next one is no int, every other int in that string will lead to an end.
I hope there is a smoother way to do this.
Replace all the non-numbers with nothing, then with that number see if the original string contains it.
String str = "foo1b2ar"; //starting string
String num = str.replaceAll("[\\D]",""); //the number it contains
return str.contains(num) && num.length() <= 2; //does the original have that number all together? and is it short?
Example:
"foo1bar" -> "1" -> Does the original contain "1"? Yes.
"f1o23obar" -> "123" -> Does the original contain "123"? No.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments