我正在尝试使用此正则表达式从URL列表中仅收集域名
val regDomains = s"""(?im)^http[s]*://[^/]+/(?!\S)""".r
在文档http://www.scala-lang.org/api/2.12.x/scala/util/matching/Regex.html中 有一个声明:
使用三引号可避免必须转义反斜杠字符
但我得到了例外
scala.StringContext $ InvalidEscapeException:无效的转义'\ S' [\ b,\ t,\ n,\ f,\ r,\,\“,\']之一
每当我尝试运行我的程序时为什么会这样?
答案 0 :(得分:0)
不需要使用字符串插值s"""..."""
,这样做会破坏正则表达式:
scala> val myRegex = """\S""".r
myRegex: scala.util.matching.Regex = \S
scala> myRegex.findAllIn("a b c 1 2 3").toList
res0: List[String] = List(a, b, c, 1, 2, 3)
scala> val myRegex = s"""\S""".r
scala.StringContext$InvalidEscapeException: invalid escape '\S' not one of [\b, \t, \n, \f, \r, \\, \", \'] at index 0 in "\S". Use \\ for literal \.
答案 1 :(得分:0)
如果您需要插入变量信息,那么原始插补器很有用:
raw"""(?im)^http[s]*://[^/]+/(?!\S)$myVar""".r