我正在使用回归表达式来查找模式,例如:
"Today USER ID: 123556 cancelled"
"January USER ID: 236477 renewed"
"February USER ID: 645689 dispute"
基本上我正在寻找包含"USER ID:"+数字的字符串。我正在使用以下代码,但它无法匹配任何内容。谁能给点建议吗?
if (myString.matches("USER ID: ([0-9]+)")) {
println(a)
}
它应该只是:
if (myString.matches("^USER ID: ([0-9]+)$")) {
正则表达式字符串中没有斜杠,用户ID:后面有一个空格
刚刚测试过,它对我的作用如下:
String string = "USER ID: 12345";
if(string.matches("^USER ID: ([0-9]+)$")){
System.out.println("matches");
}
有很多好的"正则表达式备忘单"。你可以在这里找到这样一个:http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
^USER ID: ([0-9]+)$
^^
您缺少此space
。
在Scala中(下面的标签有问题(,定义这个正则表达式
val re = "USER ID:\s+\d+".r
其中我们允许在数字序列之前有几个空格;因此对于
val a = "Today USER ID: 123556 cancelled"
re.findFirstIn(a)
Option[String] = Some(USER ID: 123556)
如果找到模式,则传递Some[String]
值,否则传递None
值。
要响应是否找到模式,请考虑
re.findFirstIn(a).isDefined
res: Boolean: true