[英]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.