我正在从 SMS 中提取数字,我只想提取以下格式之一的数字:
ID is xxx
For User: yyyy ID:xxxx
当我使用 "\\d+"
时,它会提取用户名 (yyyy
) 而不是 xxxx
。
我也尝试过 \d+ | 模式[ID:]\d+
但它只适用于带用户名的短信,不适用于第一种。
有没有办法编写一个正则表达式,如果这个模式不匹配,它会检查 Android 中的另一个模式?
此外,我尝试了 2 种不同的模式和 if 和 elseif,但这也没有用。例如:
public Pattern p = Pattern.compile("\\d+");
public Pattern q=Pattern.compile("[ID:]\\d+");
if (msgbody.contains("ID"){
final Matcher m = p.matcher(msgbody);
final Matcher n = q.matcher(msgbody);
if(m.find()){
\\first pattern p matched.
} else if(n.find()){
\\Second Pattern q matched
}
}
最佳答案
虽然完全可以根据需要测试尽可能多的正则表达式匹配,但您的两个测试用例都匹配 \\d
。然后,您就不会针对第二个表达式进行测试(这不会达到您想要的效果)。
您可以使用单个正则表达式匹配 ID is xxx
和 For User: xxxx ID:yyyy
。
使用以下表达式:
^(?:For User: \\S+ ID:|ID is )(\\d+)$
(?:
...|
...)
是一个有 2 个选项的组For User:\\S+ ID:
匹配您第二种情况的文字文本,以及任何不包含空格的用户名。ID is
从字面上匹配您的第一个案例。
(\\d+)
匹配一个数字,捕获匹配项(我们稍后可以将其引用为m.group[1]
。
代码
String msgbody = "ID is 12345"; //For testing purposes
Pattern idPatt = Pattern.compile("^(?:For User: \\S+ ID:|ID is )(\\d+)$");
Matcher m = idPatt.matcher(msgbody);
if (m.find()) {
//Print the text matched by the first group (in parentheses)
System.out.println("Matched: " + m.group(1));
} else {
System.out.println("Invalid message body");
}
关于java - 使用 2 种允许的格式匹配 SMS 消息中的数字的单一模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34033748/