简体   繁体   English

如何替换不在两个字符之间的所有字符串?

[英]How do you replace all strings that are not between two characters?

Example (replacing 'text' with '...'):示例(将 'text' 替换为 '...'):

Before: text(text)text之前:文本(文本)文本

After: ...(text)...之后:...(文本)...

In this case it is easier to find what you want to keep, and replace the rest.在这种情况下,更容易找到您想要保留的内容,并更换 rest。

Eg like this:比如像这样:

static String abbreviate(String input, String openTag, String closeTag) {
    String regex = Pattern.quote(openTag) + ".*?" + Pattern.quote(closeTag);
    StringBuilder buf = new StringBuilder();
    int start = 0;
    for (Matcher m = Pattern.compile(regex).matcher(input); m.find(); start = m.end()) {
        if (start < m.start())
            buf.append("...");
        buf.append(m.group());
    }
    if (start < input.length())
        buf.append("...");
    return buf.toString();
}

Test测试

System.out.println(abbreviate("text(text)text(text)text", "(", ")"));
System.out.println(abbreviate("text$text$text$text$text$text", "$", "$"));
System.out.println(abbreviate("text(text)text", ")", "("));

Output Output

...(text)...(text)...
...$text$...$text$...
...

You need to iterate over the characters and only append those that are between the two specified characters.您需要遍历字符并且仅 append 那些在两个指定字符之间的字符。 This can be done as follows:这可以按如下方式完成:

private String splitStr(String str, char first, char second) {
        StringBuilder sb = new StringBuilder();
        if(str.isEmpty() || str.indexOf(first) < 0 || str.indexOf(second) < 0)
            return sb.toString();
        char[] chars = str.toCharArray();
        boolean append = false;
        for(char c : chars) {
            if(c == first) {
                sb.append(c);
                append = true;
            }else if(c == second) {
                sb.append(c);
                append = false;
            }else if(append)
                sb.append(c);
        }
        return sb.toString();
}

Some sample cases are:一些示例案例是:

"text(text)text(text)text(text)text" => "(text)(text)(text)"
"text(text)text" => "(text)"
String s = "text(text)text";
String newString = s.replace("text", "...");
System.out.println(newString);      //returns ...(...)...
  1. Note that "(text)" still contains "text", the braces around it will not stop it from being replaced.请注意,“(文本)”仍然包含“文本”,它周围的大括号不会阻止它被替换。

  2. You need to assign the result to a new String to use it.您需要将结果分配给新的字符串才能使用它。 Strings are immutable字符串是不可变

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

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