我正在尝试获取一个正则表达式来匹配,然后用它获取值。例如,我想检查 1234 作为 ID,如果存在,则获取状态(在本例中为 0)。基本上是它的 id:status。这是我正在尝试的:
String topicStatus = "1234:0,567:1,89:2";
String someId = "1234";
String regex = "\\b"+someId+":[0-2]\\b";
if (topicStatus.matches(regex)) {
//How to get status?
}
我不仅不知道如何在不拆分和循环的情况下获取状态,而且不知道为什么它与正则表达式不匹配。
如有任何帮助,我们将不胜感激。谢谢。
最佳答案
使用Pattern
类
String topicStatus = "1234:0,567:1,89:2";
String someId = "1234";
String regex = "\\b"+someId+":[0-2]\\b";
Pattern MY_PATTERN = Pattern.compile(regex);
Matcher m = MY_PATTERN.matcher(topicStatus);
while (m.find()) {
String s = m.group(1);
System.out.println(s);
}
这里的关键是将您想要的位置[0-2]
括在括号中,这意味着它将被保存为第一组。然后您可以通过 group(1)
关于java - 检查 id 是否在字符串中,如果是则获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34551162/