[英]Removing literal character in regex
我有以下字符串
\\Qpipe,name=office1\\E
我正在使用一個不支持\\Q
和\\E
的簡化正則表達式庫。
我嘗試刪除它們
s.replaceAll("\\Q", "").replaceAll("\\E", "")
但是,我收到了Caused by: java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 1 \\E ^
的錯誤Caused by: java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 1 \\E ^
有任何想法嗎?
\\
是Java字符串和正則表達式引擎中的特殊轉義字符。 要將文字\\
傳遞給正則表達式引擎,您需要在Java字符串中包含\\\\\\\\
。 所以嘗試:
s.replaceAll("\\\\Q", "").replaceAll("\\\\E", "")
或者,更簡單的方法是使用replace
字符串而不是正則表達式的replace
方法:
s.replace("\\Q", "").replace("\\E", "")
例如,使用Pattern.quote()函數來轉義正則表達式中的特殊字符
s.replaceAll(Pattern.quote("\Q"), "")
replaceAll
采用正則表達式字符串。 相反,只需使用帶有文字字符串的replace
。 所以myRegexString.replace("\\\\Q", "").replace("\\\\E", "")
。
但是仍然存在為簡化的正則表達式引用特殊正則表達式字符的問題。
String.replaceAll()將正則表達式作為參數,因此您需要兩次轉義反斜杠:
s.replaceAll("\\\Q", "").replaceAll("\\\\E", "");
您也可以使用下面的。 我使用它是因為我正在匹配和替換包裹的文本,而 Q & E 將保留在模式中。 這樣就不行了。
final int flags = Pattern.LITERAL;
regex = "My regex";
pattern = Pattern.compile( regex, flags );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.