tl; dr :如何在正则表达式中为特定标记设置计数约束。
(regex-exp){constraint:max 10 only digits}
我一直试图在文本块中找到一个电话号码。 Android平台Patterns
类提供合理的覆盖率。但它有它的主要问题
因此它实际上匹配1234
,并且当存在类似my phone numbers are +19447223311 872881122
的字符串时,它将这两个数字匹配为单个数字。如果我们可以添加一个模式应该有数字{7,12}的约束,那么我猜它会解决。尽管我努力不能使其发挥作用。
这是模式的正则表达式。
public static final Pattern PHONE
= Pattern.compile( // sdd = space, dot, or dash
"(\\+[0-9]+[\\- \\.]*)?" // +<digits><sdd>*
+ "(\\([0-9]+\\)[\\- \\.]*)?" // (<digits>)<sdd>*
+ "([0-9][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit>
答案 0 :(得分:0)
在Android中没有像正则表达式约束这样的东西,并且=== Started at 2017-09-19 11:48:08
"Welcome to tictactoe server!"
"Welcome to tictactoe server!"
"Ready to rumble against Ranjan!"
"Ready to rumble against Abhijeet!"
"It is not your turn yet!"
"It is not your turn yet!"
=== Ended at 2017-09-19 11:48:08
=== successfully completed test case
=== Returned value: {make_move,a3}
模式是预编译的,你也不能扩展它。
我会这样做:
PHONE
给出了这个结果:
Pattern constraint = Pattern.compile("\\+?\\d{7,12}");
Matcher constraint_matcher = constraint.matcher("I will be home by 12:30 and if you have anything " +
"urgent call me at 901 101 0101, and my extension is 1021 +19447223311 872881122 ");
while (constraint_matcher.find()) {
Matcher phone_number_matcher = Patterns.PHONE.matcher(constraint_matcher.group(0));
if (phone_number_matcher.find()) {
Log.d("MATCH", phone_number_matcher.group(0));
}
}