6 个答案:
答案 0 :(得分:9)
if (myString.matches(".*\\+[0-9]+now.*"))
此外,+是一个特殊的正则表达式字符,这就是你需要逃避它的原因。
如果您需要捕获数字,请使用Pattern和Matcher:
Pattern p = Pattern.compile("\\+([0-9]+)now");
Matcher m = p.matcher(myString);
while (m.find()) {
System.out.println(m.group(1));
}
()是一个捕获组,这意味着它会告诉正则表达式引擎存储匹配的内容,以便您稍后可以使用group()检索它。
答案 1 :(得分:6)
试试这个......
Pattern pat = Pattern.compile("\\+\\d+now");
Matcher mat = pat.matcher("Input_Text");
while(mat.find()){
// Do whatever you want to do with the data now...
}
答案 2 :(得分:3)
你需要逃避第一个' +'像这样:
if(myString.matches("\\+[0-9]+now"));
+表示"在字符串中找到一个+"而不是"找到这个角色1次或多次"
答案 3 :(得分:2)
我假设您要么匹配字符串,要么可能提取中间的数字?在你的情况下,问题是+我们是一个特殊字符,因此你需要像这样转义它:\\+,所以你的正则表达式变成\\+[0-9]+now。
至于你的第二个问题,.contains方法接受一个字符串,而不是正则表达式,因此你的代码将不起作用。
String str = "+124now";
Pattern p = Pattern.compile("\\+(\\d+)now");
Matcher m = p.matcher(str);
while (m.find())
{
System.out.println(m.group(1));
}
在这种情况下,我已经提取了数字,以防这是您所追求的。
答案 4 :(得分:1)
方法contains不会将其参数解释为正则表达式。请改用方法matches。您也必须逃离+,如下所示:
if (myString.matches("\\+\\d+now"))
答案 5 :(得分:1)
由于您说字符串始终以+开头并始终以now结尾,为什么不检查这是否为真。如果没有,则出现问题。
String[] vals = {"+124now", "+78now", "-124now", "+124new"};
for (String s : vals) {
if (s.matches("^\\+(\\d+)now$")) {
System.out.println(s + " matches.");
} else {
System.out.println(s + " does not match.");
}
}
当然,如果您想捕获数字,那么请使用像npinti建议的匹配器。
编辑:
以下是获取数字的方法:
Pattern p = Pattern.compile("^\\+(\\d+)now$");
for (String s : vals) {
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(s + " matches and the number is: " + m.group(1));
} else {
System.out.println(s + " does not match.");
}
}