我正在尝试从多行正则表达式中捕获内容。它不匹配。
val text = """<p>line1
line2</p>"""
val regex = """(?m)<p>(.*?)</p>""".r
var result = regex.findFirstIn(text).getOrElse("")
返回空。
我把m - 标志放在多线上,但在这种情况下似乎没有帮助。
如果我删除换行符,则正则表达式可以正常工作。
我还发现了this但无法正常工作。
如何匹配<p>
元素之间的内容?我想要介于两者之间的所有内容,也包括换行符。
提前致谢!
答案 0 :(得分:24)
如果要在scala中激活dotall模式,则必须使用(?s)
代替(?m)
(?s)
表示点可以匹配换行符
(?m)
表示^
和$
代表开头和行尾
答案 1 :(得分:5)
如果此时不明显,“我如何匹配内容”:
scala> val regex = """(?s)<p>(.*?)</p>""".r
scala> (regex findFirstMatchIn text).get group 1
res52: String =
line1
line2
更具惯用力,
scala> text match { case regex(content) => content }
res0: String =
line1
line2
scala> val embedded = s"stuff${text}morestuff"
embedded: String =
stuff<p>line1
line2</p>morestuff
scala> val regex = """(?s)<p>(.*?)</p>""".r.unanchored
regex: scala.util.matching.UnanchoredRegex = (?s)<p>(.*?)</p>
scala> embedded match { case regex(content) => content }
res1: String =
line1
line2