下面我试图用替换字符串xxx替换精确的搜索字符串。我有字符串原始类似于Java日志消息。正如你可以看到搜索字符串是否是“变量”我能够成功地用xxx替换它,但是当搜索字符串是“variable.method()”或“variable.method2()”时,我无法替换它。我在这里做错了吗?
val original = """variable+ " is in " + variable.method() + " and " + variable.method2()"""
val replaceStr = "xxx"
val searchStr = "variable.method()" // This can change like in the output below
val variableExtracter = ("(?<=^|\\s|\\+)"+searchStr+"(?=\\s|$|\\+)").r
print("Search string : " + searchStr + "\n")
print("Original :" + original + "\n")
val formatted = variableExtracter.replaceAllIn(original, replaceStr)
print("Formatted :" + formatted + "\n")
Output:
Search string : variable //CORRECT OUTPUT
Original :variable+ " is in " + variable.method() + " and " + variable.method2()
Formatted :xxx+ " is in " + variable.method() + " and " + variable.method2()
---
Search string : variable.method()
Original :variable+ " is in " + variable.method() + " and " + variable.method2()
Formatted :variable+ " is in " + variable.method() + " and " + variable.method2()
//EXPECTED OUTPUT: variable+ " is in " + xxx + " and " + variable.method2()
---
Search string : variable.method2()
Original :variable+ " is in " + variable.method() + " and " + variable.method2()
Formatted :variable+ " is in " + variable.method() + " and " + variable.method2()
//EXPECTED OUTPUT:variable+ " is in " + variable.method() + " and " + xxx
---
Search string : variable.method()
Original :variable.method()+ " has " + variable + " and " + variable.method2()
Formatted :variable.method()+ " has " + variable + " and " + variable.method2()
//EXPECTED OUTPUT:xxx+ " has " + variable + " and " + variable.method2()
答案 0 :(得分:1)
编辑:
您可以使用Java Pattern quote method Pattern.quote(searchStr)
将字符串换成\Q
和\E
。
scala> import java.util.regex.Pattern
import java.util.regex.Pattern
scala> val variableExtracter = ("(?<=^|\\s|\\+)"+Pattern.quote(searchStr)+"(?=\\s|$|\\+)").r
variableExtracter: scala.util.matching.Regex = (?<=^|\s|\+)\Qvariable.method2()\E(?=\s|$|\+)
scala> print("Search string : " + searchStr + "\n")
Search string : variable.method2()
scala> print("Original :" + original + "\n")
Original :variable+ " is in " + variable.method() + " and " + variable.method2()
scala> val formatted = variableExtracter.replaceAllIn(original, replaceStr)
formatted: String = variable+ " is in " + variable.method() + " and " + xxx
scala> print("Formatted :" + formatted + "\n")
Formatted :variable+ " is in " + variable.method() + " and " + xxx
scala> val searchStr = "variable.method()"
searchStr: java.lang.String = variable.method()
scala> val variableExtracter = ("(?<=^|\\s|\\+)"+Pattern.quote(searchStr)+"(?=\\s|$|\\+)").r
variableExtracter: scala.util.matching.Regex = (?<=^|\s|\+)\Qvariable.method()\E(?=\s|$|\+)
scala> val formatted = variableExtracter.replaceAllIn(original, replaceStr)
formatted: String = variable+ " is in " + xxx + " and " + variable.method2()