下面我试图用替换字符串 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()