【问题标题】:How to replace any of the substrings in a string with empty substring "" (remove substring) in java如何在java中用空子字符串“”(删除子字符串)替换字符串中的任何子字符串
【发布时间】:2016-08-10 10:12:03
【问题描述】:

我想在一个字符串中只允许几个子字符串(允许的单词)。我想删除其他子字符串。

所以我想替换所有单词,除了 "abc" 、 "def" 和 "ghi" 等少数单词。

我想要这样的东西。 str.replaceAll("^[abc],"").replaceAll("^[def],"").......(语法不正确)

输入:字符串:"abcxyzorkdefa" 允许的词:{"abc","def"}

输出:“abcdef”;

如何做到这一点? 提前致谢。

【问题讨论】:

  • 你试过replaceAll("[^abc|^def]","");

标签: java string replace substring


【解决方案1】:

这是一种更类似于 C 的方法,但使用 Java 的 String.startsWith 来匹配模式。该方法遍历提供的字符串,将匹配的模式保存到找到它们的结果中的结果字符串中。

您只需要确保包含较小模式的任何较长模式位于模式数组的前面(因此"abcd" 位于"abc" 之前)。

class RemoveNegated {
    public static String removeAllNegated(String s, List<String> list) {
        StringBuilder result = new StringBuilder();
        // Move along the string from the front
        while (s.length() > 0) {
            boolean match = false;
            // Try matching a pattern
            for (String p : list) {
                // If the pattern is matched
                if (s.toLowerCase().startsWith(p.toLowerCase())) {
                    // Save it
                    result.append(p);
                    // Move along the string
                    s = s.substring(p.length());
                    // Signal a match
                    match = true;
                        break;
                    }
                }
                // If there was no match, move along the string
                if (!match) {
                s = s.substring(1);
            }
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String s = "abcxyzorkdefaef";
        s = removeAllNegated(s, Arrays.asList("abc", "def", "ghi"));
        System.out.println(s);
    }
}

打印:abcdef

【讨论】:

  • 感谢@Billy Brown 的解决方案。进行了编辑以使其成为区分大小写的解决方案:)
  • @omkarsirra 区分大小写。你的意思是不区分大小写吗?
  • 对不起。是的,不区分大小写
  • @omkarsirra 如果我的回答是正确的,你能这样标记吗?
猜你喜欢
  • 1970-01-01
  • 2022-01-22
  • 2016-12-24
  • 1970-01-01
  • 2012-08-09
  • 2023-03-25
  • 2018-04-01
  • 1970-01-01
  • 2012-04-03
相关资源
最近更新 更多