注意:我不得不簡化我的實際使用情況,以備用很多背景故事。所以如果你對這個問題的第一反應是:爲什麼你會這樣做,相信我,我只需要。從Groovy表達式中雙重轉義正則表達式
我正在嘗試編寫一個Groovy表達式,它用單引號(「'
」)替換出現在字符串中的雙引號(「"
」)。
// BEFORE: Replace my "double" quotes with 'single' quotes.
String toReplace = "Replace my \"double-quotes\" with 'single' quotes.";
// Wrong: compiler error
String replacerExpression = "toReplace.replace(""", "'");";
Binding binding = new Binding();
binding.setVariable("toReplace", toReplace);
GroovyShell shell = new GroovyShell(binding);
// AFTER: Replace my 'double' quotes with 'single' quotes.
String replacedString = (String)shell.evaluate(replacerExpression);
的問題是,我在哪裏我指定replacerExpression
線得到一個編譯錯誤:令牌 「」 toReplace.replace( 「
語法錯誤」,{預期
我認爲這是因爲我需要轉義包含雙引號字符(「」「)的字符串,但由於它是一個字符串在字符串內,我不確定如何在這裏正確地轉義它。想法?提前致謝!
感謝@ataylor(+1),但您的建議會產生以下編譯器rrors:'多個標記在該行 \t - 賦值的左邊必須是一個變量 \t - 字符串文字不正確的關閉雙引號 \t - 語法錯誤,插入「AssignmentOperator表達式」以完成作業 \t - 語法錯誤,插入「;」完成聲明 \t - 有關令牌的語法錯誤(預期會改變) – IAmYourFaja
@IAmYourFaja第二種使用'「」「'的解決方案完美無瑕,您如何運行腳本? – dmahapatro
哦,我明白了,外部代碼是Java, – ataylor