![](/img/trans.png)
[英]How to match a string between keywords containing any symbol (including new lines) in regex
[英]How to match string containing plus symbol (+) in scala?
我正在尝试匹配两个带有“+”符号的字符串。
val mystring = "test+string"
val tomatch = "test+string"
mystring.matches(tomatch)
This returns False.
试图用\\ +逃避+但是它不起作用。
转义+
是正确的,因为\\+
匹配文字+
。 还有更多字符需要以正则表达式模式进行转义,请参阅在正则表达式中必须转义哪些特殊字符?
在Scala中,您可以使用"""...."""
三重引用的字符串文字只使用1个反斜杠。 请参阅Scala正则表达式帮助 :
由于转义不是在多行字符串文字中处理的,因此使用三引号可以避免必须转义反斜杠字符,因此
"\\\\d"
可以写为"""\\d"""
。 使用某些插值器可以获得相同的结果,例如raw"\\d".r
或也可以编译正则Regex
的自定义插值器r"\\d"
。
所以,使用
val mystring = "test+string"
val tomatch = """test\+string"""
mystring.matches(tomatch)
请参阅Scala演示
否则,在常规(非“原始”)字符串文字中,您需要双反斜杠:
val tomatch = "test\\+string"
如果整个字符串模式应被视为文字字符串 ,请使用
import scala.util.matching.Regex
接着
val tomatch = Regex.quote("test+string")
Regex.quote
将逃脱应该正确转义的所有特殊字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.