簡體   English   中英

java字符串替換方法有效但拋出replaceAll錯誤

[英]java String replace method works but throwing error with replaceAll

我有一個字符串而且我想替換{to \\ {...當我使用replace方法然后它可以工作但是當我使用replaceAll然后它給出錯誤,如Illegal repetition是什么原因?

String s = "One{ two } three {{{ four}";
System.out.println(s.replace("{", "\\{"));
System.out.println(s.replaceAll("{", "\\{"));

預期輸出為 - 一個\\ {兩個}三個\\ {\\ {\\ {{四個}

正如解釋的那樣String::replaceAll期望regexStrinng::replace期望charSequence 所以你必須同時逃避\\{以便按照你的預期進行匹配。

String s = "One{ two } three {{{ four}";

System.out.println(s);
System.out.println(s.replace("{", "\\{"));
System.out.println(s.replaceAll("\\{", "\\\\{"));

輸出:

One{ two } three {{{ four}
One\{ two } three \{\{\{ four}
One\{ two } three \{\{\{ four}

String replaceAll期望regex,而replace期望charSequence。 因此修改代碼

System.out.println(s.replaceAll("\\{", "\\{"));

應該管用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM