RegExp GWT/Javascript的测试方法
我想使用正则表达式检测 String
是否为小数。我的问题更多的是如何使用正则表达式机制,而不是检测 String
是小数。我使用 GWT
提供的 RegExp
类。
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]));
}
输出:
one false false null
+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
我期望 String.matches()
和 RegExp.test()
方法返回相同的结果。
- 那么有什么区别 两种方法?
- 如何使用
RegExp.test()
获得相同的行为?
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 null
+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.
- So what's the difference between
both methods? - How to use the
RegExp.test()
to get the same behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将正则表达式更改为
解释
双重转义是因为我们在Java中......
正则表达式以
^
开头,强制正则表达式从字符串的开头进行匹配。regex end with
$
强制正则表达式从字符串的最末尾开始匹配。这就是您应该如何让 String.matches() 执行与 GWT RegExp.test() 相同的操作
Try to change the regex to
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()
我不知道有什么区别,但我想说
RegExp.test()
是正确的,因为只要字符串中有数字,您的正则表达式就会匹配,并且String.matches( )
的行为类似于正则表达式周围的锚点。您的非捕获组是可选的,因此无论周围是什么,一个
\\d
([0-9]
) 就足以匹配。当您向正则表达式添加锚点时,这意味着它必须从头到尾匹配字符串,然后
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 andString.matches()
behaves like there where anchors around the regex.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.