Integer in a string with 1 or 2 digits

Sorry, I don't know if you understand what I want to do, and I'm also not 100% sure if this can be done with regular expressions, but maybe there is a better solution than the one in my mind ...

I want to create a function that takes a string as a parameter and checks if there is an integer string in that string (that's the simple part) The function should return false if there is an integer but with more than two digits or places.

Really:

  • foo1bar
  • foobar1
  • f12obar
  • 12foobar

Invalid

  • f1o2obar
  • f1o23obar

So the simple part, regex for 1 or 2 digits doesn't really matter

[0-9]{1,2}

      

Another way, which I find to be pretty bad code, is to loop through the entire string and count each int. Once I saw that one and the next one is not an int, every other int on that line will end up.

Hopefully there is a smoother way to do this.

+3


source to share


3 answers


Replace all non-numbers with nothing, then with that number see if the original string contains.

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" → Is there a "1" in the original? Yes.

"f1o23obar" → "123" → Is there "123" in the original? Not.

+3


source


You can use the following idiom to match an integer with String

just one 1 or 2 digit number:

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

      

+2


source


Regex :

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

      

You will notice that in the linked demo I have supplied the bindings ^

and $

and used a multi-line modifier m

... this may or may not be necessary depending on your implementation.

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

0


source







All Articles