本文介绍了Scala:如何构造包含变量的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试包含我之前定义的变量的 regex 是否与字符串匹配.

I want to test if a regex including a variable that I defined before matches a string.

例如我想做:

val value = "abc"
regex = "[^a-z]".r + value //something like that
if(regex matches ".abc") print("ok, it works")

所以我的问题是:如何在 Scala 中添加构造一个包含变量的正则表达式?

推荐答案

您必须引用值字符串以防止特殊的正则表达式语法.

You must quote the value string to protect against special regex syntax.

scala> val value = "*"
value: String = *

scala> val oops = """[^a-z]""" + value r
oops: scala.util.matching.Regex = [^a-z]*

scala> ".*" match { case oops() => }

scala> ".....*" match { case oops() => }

他们在 Scala API 中添加了引用:

They added quoting to the Scala API:

scala> import util.matching._
import util.matching._

scala> val ok = """[^a-z]""" + Regex.quote(value) r
ok: scala.util.matching.Regex = [^a-z]\Q*\E

scala> ".*" match { case ok() => }

scala> ".....*" match { case ok() => }
scala.MatchError: .....* (of class java.lang.String)
  ... 33 elided

您还可以概括该模式并进行其他检查:

You could also generalize the pattern and do additional checks:

scala> val r = """\W(\w+)""".r
r: scala.util.matching.Regex = \W(\w+)

scala> ".abc" match { case r(s) if s == "abc" => }

解析和构建正则表达式本身的成本相对较高,因此通常最好使用通用模式进行一次.

Parsing and building the regex itself is relatively expensive, so usually it's desirable to do it once with a general pattern.

这篇关于Scala:如何构造包含变量的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 15:47