2014-12-07 83 views
1

我有以下代码:如何使用正则表达式匹配整个字符串

def main(args: Array[String]) { 
     val it = ("\\b" + "'as" + "\\b").r.findAllMatchIn("'as you are a's".toLowerCase()); 
     val lst = it.map(_.start).toList 
     print(lst) 
} 

我希望答案是List(0)(因为它匹配'as和指标应0),但它给了我List()

此外,

def main(args: Array[String]) { 
     val it = ("\\b" + "as" + "\\b").r.findAllMatchIn("'as you are a's".toLowerCase()); 
     val lst = it.map(_.start).toList 
     print(lst) 
    } 

这给我的回答List(1)但我预计一nswer是List(),因为我想匹配整个事情(需要精确匹配'as),这就是为什么我用\b这里

但它运行良好:

def main(args: Array[String]) { 
     val it = ("\\b" + "a's" + "\\b").r.findAllMatchIn("'as you are a's".toLowerCase()); 
     val lst = it.map(_.start).toList 
     print(lst) 
    } 

它返回List(12)这就是我想要的(因为它匹配a's和索引应该是12)。

我不明白为什么它不起作用,当我把'放在字的前面。我怎样才能做到这一点?

回答

1

如果之后的第一个字符不是字母或其他单词字符,则问题是\b不匹配。所以当它跟着'时它不匹配。请参阅:http://www.regular-expressions.info/wordboundaries.html

编辑:

val it = ("(?:\\b|')" + "as" + "\\b").r.findAllMatchIn("'as you are a's".toLowerCase()) 
+0

@yeah,所以我怎么整字符串匹配? – CSnerd 2014-12-07 18:10:06

+0

无论如何,您并不期望与整个字符串匹配......只要可能,只有“as”。从正面删除'\\ b'。 – 2014-12-07 18:12:18

+0

一个简单的例子,用'(?:\ b |')'预先检查:http://fiddle.re/ta2bn6 – 2014-12-07 19:08:24