Integer in String with 1 or 2 digits

167 views Asked by At

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:

  • foo1bar
  • foobar1
  • f12obar
  • 12foobar

Invalid

  • f1o2obar
  • f1o23obar

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.

3

There are 3 answers

0
DeadChex On BEST ANSWER

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.

4
Sam On

Regex:

[^0-9]*[0-9]{1,2}[^0-9]*

You'll notice that in the linked demo, I put ^ and $ anchors and used the m multi-line modifier...this may or may not be necessary depending on your implementation.

Essentially, I'm looking for 1-2 digits surrounded by 0+ non-digits.

0
Mena On

You can use the following idiom to match the whole String against only 1 number with 1 or 2 digits:

String[] test = {
    "foo1bar",
    "foobar1",
    "f12obar",
    "12foobar",
    "f1o2obar",
    "f1o23obar"
};
for (String s: test) {
    //                   | matching the whole string
    //                   |       | non-digit, 0 or more times, reluctantly quantified
    //                   |       |     | 1 or 2 digits
    //                   |       |     |       | non digit, 0 or more times, 
    //                   |       |     |       | reluctantly quantified
    System.out.println(s.matches("\\D*?\\d{1,2}\\D*?"));
}

Output

true
true
true
true
false
false