字符串替换功能

use*_*778 1 java string

我有以下字符串

String str = "replace :) :) with some other string";
Run Code Online (Sandbox Code Playgroud)

我想:)用其他字符串替换第一次出现

我用过 str.replaceFirst(":)","hi");

它给出了以下例外

"无与伦比的收盘")'"

我尝试使用replace函数,但它取代了所有的出现:).

Gre*_*ill 10

replaceFirst方法将正则表达式作为其第一个参数.由于)是正则表达式中的特殊字符,因此必须引用它.尝试:

str.replaceFirst(":\\)", "hi");
Run Code Online (Sandbox Code Playgroud)

需要双反斜杠,因为双引号字符串也使用反斜杠作为引号字符.


Tor*_*gen 5

replaceFirst()的第一个参数是一个正则表达式,而不仅仅是一个字符序列.在正则表达式中,parantheses具有特殊意义.你应该像这样逃避paranthesis:

str = str.replaceFirst(":\\)", "hi");
Run Code Online (Sandbox Code Playgroud)