提问人:hden 提问时间:6/25/2016 更新时间:6/25/2016 访问量:167
返回不匹配的正则表达式 Scala 的第一个实例
return first instance of unmatched regex scala
问:
有没有办法使用 Scala 的正则表达式库返回 2 个字符串之间不匹配字符串的第一个实例?
例如:
val a = "some text abc123 some more text"
val b = "some text xyz some more text"
a.firstUnmatched(b) = "abc123"
答:
1赞
LukStorms
6/25/2016
#1
正则表达式适用于基于模式的字符串匹配和替换。
但是要寻找字符串之间的差异?不完全是。
但是,可用于查找差异。diff
object Main extends App {
val a = "some text abc123 some more text 321abc"
val b = "some text xyz some more text zyx"
val firstdiff = (a.split(" ") diff b.split(" "))(0)
println(firstdiff)
}
打印“ABC123”
正则表达式到底是需要的吗?然后意识到拆分可以用正则表达式匹配来代替。
此示例中的正则表达式模式查找单词:
val reg = "\\w+".r
val firstdiff = (reg.findAllIn(a).toList diff reg.findAllIn(b).toList)(0)
评论
val regex = str.r
str
a.split(" ").zip(b.split(" ")).dropWhile { case (a, b) => a == b }.head._1