开发者

test method of RegExp GWT/Javascript

I want to detect if a String is a decimal by using a regular expression. My question is more on how to use the regular expression mechanism than detecting that a String is a decimal. I use the RegExp class provided by GWT.

        String regexDecimal = "\\d+(?:\\.\\d+)?";
        RegExp regex = RegExp.compile(regexDecimal);
        String[] decimals = { "one", "+2", "-2", ".4", "-.4", ".5", "2.5" };
        for (int i = 0; i < decimals.length; i++) {
            System.out.println(decimals[i] + " "
                    + decimals[i].matches(regexDecimal) + " "
                    + regex.test(decimals[i]) + " "
                    + regex.exec(decimals[i]));
        }

The output:

one false false nul开发者_JS百科l
+2 false true 2
-2 false true 2
.4 false true 4
-.4 false true 4
.5 false true 5
2.5 true true 2.5

I was expecting that both methods String.matches() and RegExp.test() return the same result.

  1. So what's the difference between both methods?
  2. How to use the RegExp.test() to get the same behaviour?


Try to change the regex to

"^\\d+(?:\\.\\d+)?$"

explain
double escape is because we're in Java...
regex start with ^ to forces the regex to match from the very start of the string.
regex end with $ to forces the regex to match from the very end of the string.

this is how you should get String.matches() to do the same as GWT RegExp.test()


I don't know the difference, but I would say that RegExp.test() is correct, because your regex matches as soon as there is a digit within your string and String.matches() behaves like there where anchors around the regex.

\\d+(?:\\.\\d+)?

Your non capturing group is optional, so one \\d ([0-9]) is enough to match, no matter what is around.

When you add anchors to your regex, that means it has to match the string from the start to the end, then RegExp.test() will probably show the same results.

^\\d+(?:\\.\\d+)?$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜