简体   繁体   English

替换 Java 中的子字符串

[英]Replace a substring in Java

What is a proper way to replace a part of string, matching some criteria, for example, if I have this text:什么是替换字符串的一部分,匹配某些条件的正确方法,例如,如果我有这个文本:

"some_text1((some_text2) and 1)some_text3"

I want to convert it into:我想把它转换成:

"some_text1(some_text2)some_text3"

In this example, the criteria is: if there is ( ... and 1) , I want to replace it with ... (some text, I don't know what is it).在这个例子中,标准是:如果有( ... and 1) ,我想用...替换它(一些文字,我不知道它是什么)。

Edit: According to answers I've written this function:编辑:根据我写的这个函数的答案:

static String replaceRecursive(String str, String pattern, String matcher) {
    String res = str.replaceAll(pattern, matcher);
    if (res == str) {
        return res;
    }
    return replaceRecursive(res, pattern, matcher);
}

usage:用法:

String str = "((((X and 1) and Y) and 1) or Z)";

System.out.println(replaceRecursive(str, "\\((.*) and 1\\)", "$1"));

It seems to be working它似乎正在工作

Update: It still doesn't work.更新:它仍然不起作用。 There is problem in brackets.括号里有问题。 For example, if str = "((some_text1)((some_text2) and 1))" , the first opening bracket will be removed, instead of the third one.例如,如果str = "((some_text1)((some_text2) and 1))" ,第一个str = "((some_text1)((some_text2) and 1))"括号将被删除,而不是第三个。

How about something like this:这样的事情怎么样:

String s = "some_text1((some_text2) and 1)some_text3";
System.out.println(s.replaceAll("\\(.*?(\\(.*?\\)).*?\\)", "$1"));

This matches nested parenthesis and puts the inner parenthesis in match group 1, which is then used in the replacement string, effectively discarding the outer parenthesis (and its contents).这匹配嵌套括号并将内括号放入匹配组 1,然后在替换字符串中使用,有效地丢弃外括号(及其内容)。

Needless to say, if either some_text1 or some_text3 contains parenthesis, things will go wrong.不用说,如果some_text1some_text3包含括号,事情就会出错。

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

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