1

下面我试图用替换字符串 xxx 替换确切的搜索字符串。我有类似于 java 日志消息的字符串 original。如您所见,如果搜索字符串是“变量”,我可以成功地将其替换为 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()
4

1 回答 1

1

编辑:

您可以使用Java 模式引用方法 Pattern.quote(searchStr)\Qand包装您的字符串\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()
于 2012-12-03T16:44:03.367 回答