简体   繁体   English

在java中的String replaceAll方法未提供预期的结果

[英]In java String replaceAll method not giving expected result

Following is the program which is not giving expecting result with replaceAll method. 以下是使用replaceAll方法未给出预期结果的程序。

public class HelloWorld{
     public static void main(String []args){
         String source = "Stack Overflow is a question and answer (site) for professional.";
         String txt1 = "question and answer (site) for";
        String text2 = "changed question and answer (site) for";
        source = source.replaceAll(txt1, text2);
        System.out.println(source);
     }
}

If I remove parenthesis (ie brackets) in source, text1 and text2 for a word "site" it is giving proper result. 如果我在源,text1和text2中删除单词“ site”的括号(即括号),则将得到正确的结果。 Can some one help me what would be the problem in it? 有人可以帮我解决问题吗?

replaceAll method takes regular expression as arguements. replaceAll方法以正则表达式为依据。 And as the parentheses is a character used in regex so those are not recognized directly. 由于括号是正则表达式中使用的字符,因此这些字符不能直接识别。 you can do use Pattern.quote to get the literal string. 您可以使用Pattern.quote来获取文字字符串。

Parentheses are used for grouping. 括号用于分组。 If you want them to be literal, 如果您希望它们是文字,

String txt1 = "question and answer \\(site\\) for";

This applies only to the pattern, not the replacement string. 这仅适用于模式,不适用于替换字符串。

Grouping is used in regex for accessing parts of the matched string if you use wildcards. 如果使用通配符,则在正则表达式中使用分组来访问匹配字符串的某些部分。

"abc(\\d+)def"

With this you can, after the match, determined the digits matched by the middle part. 这样,您可以在匹配后确定中间部分匹配的数字。

Or you use 或者你用

source = source.replace(txt1, text2);

without any regex wizardry. 没有任何正则表达式向导。 (It still replaces all occurrences.) (它仍然替换所有出现的事件。)

If you are just going to replace plain strings and are not using regular expressions at all, you don't need to change the parentheses. 如果您只是要替换纯字符串并且根本不使用正则表达式,则无需更改括号。 Instead you just let Java escape all special characters using Pattern.quote in the searched string like that: 相反,您只需要使用搜索字符串中的Pattern.quote让Java转义所有特殊字符,如下所示:

public class HelloWorld{
     public static void main(String []args){
         String source = "Stack Overflow is a question and answer (site) for professional.";
         String txt1 = "question and answer (site) for";
        String text2 = "changed question and answer (site) for";
        source = source.replaceAll(Pattern.quote(txt1), text2);
        System.out.println(source);
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM