fgonzalez
fgonzalez

Reputation: 3877

Creating a regular expression for a URI path

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?

Upvotes: 1

Views: 1078

Answers (1)

badperson
badperson

Reputation: 1614

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

Upvotes: 1

Related Questions