1

I need to parse this String "/<productId>/save" and I have to ensure that productId is an unsigned integer of 32 bits.

Of course I could split the String using the character "/" and then in the returned array try to cast the product Id to an Integer and see if I get an exception or not, but it does not seem a very elegant solution.

Instead I've tried using this regular expression boolean match=path.matches("\\/\\d+\\/save"); which works fine but it is not respecting the restriction of the integer of 32 bits, basically I can enter a number of any size.

I.e the followinf string /44444444444444444/save"; matches the regular expression.

What is the more elegant way to do this? Could you recommend me any approach?

fgonzalez
  • 3,787
  • 7
  • 45
  • 79
  • The most elegant way is clearly to not try to check the number with regex (it's possible but ugly and inefficient), so extract it and check it with a simple comparison. If you want you can limit the number of digits in the pattern. – Casimir et Hippolyte Nov 30 '16 at 22:27
  • 5
    Duplicate of http://stackoverflow.com/questions/20793578/regex-for-a-valid-32-bit-signed-integer – 0xA2C2A Nov 30 '16 at 22:28
  • RegEx can't be used to check integral bounds without some _really_ ugly regex. – Qix - MONICA WAS MISTREATED Nov 30 '16 at 22:28
  • To give an idea, for a 8bits number you must write something like: `1[0-9]{0,2}|2(?:[0-4][0-9]?|5[0-5]?|[6-9])?|[3-9][0-9]?`, imagine the same for a 32bits number. – Casimir et Hippolyte Nov 30 '16 at 22:36
  • but poster is also looking for the num in the middle of the URI pattern, so isn't the regex the best solution there? – badperson Nov 30 '16 at 22:42
  • Ask yourself about the purpose of Url-Rewrites: It should make readable URLs - Search-Engine-Friendly (even if Search Engines don't care about it anyway). So, you'd better keep "abstract" information like ids out of this url: `http://mypage.com/action/save/?id=4444444444444444` Then - if your ID does not rely on regex, but the regular parameter-workflow, java should just convert it to long, float or whatever. Trying to handle "System-Limits" will just move the case towards the "next" limit without any real resolution of the actual problem. – dognose Nov 30 '16 at 22:53

1 Answers1

1

Here's one solution that deals with the possibility the number is too large:

@Test
public void testMatchIntWithRegex() {
    String rgx = "\\/(\\d+)\\/save";
    String example = "/423/save";
    String exampleB = "/423666666666666666666666666666666666666666/save";

    Pattern p = Pattern.compile(rgx);
    Matcher m = p.matcher(example);
    if(m.find()){
        String sInt = m.group(1);
        try{
            int num = Integer.parseInt(sInt);
            System.out.println("num is : " + num);
        } catch(NumberFormatException e){
            e.printStackTrace();
        }


    }

}

example works while exampleB throws an exception

badperson
  • 1,554
  • 3
  • 19
  • 41