scala 如何在不知道正则表达式匹配的情况下使用正则表达式提取子字符串(组)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11810615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do I extract substring (group) using regex without knowing if regex matches?
提问by Ixx
I want to use this
我想用这个
val r = """^myprefix:(.*)""".r
val r(suffix) = line
println(suffix)
But it gives an error when the string doesn't match. How do I use a similar construct where matching is optional?
但是当字符串不匹配时它会出错。我如何使用类似的结构,其中匹配是可选的?
Edit: To make it clear, I need the group (.*)
编辑:为了清楚起见,我需要该组 (.*)
回答by Kim Stebel
You can extract match groups via pattern matching.
您可以通过模式匹配提取匹配组。
val r = """^myprefix:(.*)""".r
line match {
case r(group) => group
case _ => ""
}
Another way using Option:
另一种使用方式Option:
Option(line) collect { case r(group) => group }
回答by Luigi Plinge
"""^myprefix:(.*)""".r // Regex
.findFirstMatchIn(line) // Option[Match]
.map(_ group 1) // Option[String]
This has the advantage that you can write it as a one-liner without needing to assign the regex to an intermediate value r.
这样做的好处是您可以将其编写为单行,而无需将正则表达式分配给中间值r。
In case you're wondering, group 0 is the matched string while group 1 etc are the capture groups.
如果您想知道,组 0 是匹配的字符串,而组 1 等是捕获组。
回答by viktortnk
try
尝试
r.findFirstIn(line)
UPD:
更新:
scala> val rgx = """^myprefix:(.*)""".r
rgx: scala.util.matching.Regex = ^myprefix:(.*)
scala> val line = "myprefix:value"
line: java.lang.String = myprefix:value
scala> for (rgx(group) <- rgx.findFirstIn(line)) yield group
res0: Option[String] = Some(value)

