1

以下では、正確な検索文字列を置換文字列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()
4

1 に答える 1

1

編集:

Java パターン の quote メソッドを使用して、文字列をandPattern.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()
于 2012-12-03T16:44:03.367 に答える