为URI路径创建正则表达式

时间:2016-11-30 22:19:49

标签: java regex

我需要解析这个字符串"/<productId>/save",我必须确保productId是一个32位的无符号整数。

当然我可以使用字符&#34; /&#34;来分割String。然后在返回的数组中尝试将产品Id转换为Integer,看看我是否得到异常,但它似乎不是一个非常优雅的解决方案。

相反,我尝试使用这个正则表达式boolean match=path.matches("\\/\\d+\\/save");,它工作正常,但它不遵守32位整数的限制,基本上我可以输入任意大小的数字。

即followinf字符串/44444444444444444/save";与正则表达式匹配。

更优雅的方法是什么?你能推荐我任何方法吗?

1 个答案:

答案 0 :(得分:1)

这是一个解决数字过大的可能性的解决方案:

@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();
        }


    }

}

示例有效,而exampleB抛出异常

相关问题