字符串操作 - 从字符串中删除char

时间:2010-06-25 15:04:03

标签: java regex string

我目前在java中有以下字符串:

"Blah, blah, blah,~Part One, Part Two~,blah blah"

我需要删除~字符之间的逗号,以便读取。

"Blah, blah, blah,~Part One Part Two~,blah blah"

有人可以帮帮我吗?

非常感谢,

4 个答案:

答案 0 :(得分:5)

    String[] tests = {
        "a,b,c,d,e,f",
        "a,b,~c~,d,e",
        "~a,b,c,d,e~",
        "a,b,c,~d,e,f~,g,h,i,~j,k,l,~m,n,o~,q,r,~s,t,u",
    };
    for (String test : tests) {
        System.out.println(
            test.replaceAll(
                "(^[^~]*~)|([^~]*$)|([^,~]*),|([^,~]*~[^~]*~)",
                "$1$2$3$4"
            )
        );
    }

以上版画:

a,b,c,d,e,f
a,b,~c~,d,e
~abcde~
a,b,c,~def~,g,h,i,~jkl~m,n,o~qr~s,t,u

如何运作

有4个案例:

  • 我们在字符串的开头,“在外面”
    • 只需匹配,直到我们找到第一个~,所以下次我们会“在里面”
    • 所以,(^[^~]*~)
  • 在字符串结尾之前不再有~
    • 如果偶数~,我们就会“在外面”
    • 只是匹配到最后
    • 所以,([^~]*$)
  • 如果不是上述内容,我们就是“内部”
    • 继续~之前找到下一个逗号(所以我们仍在“内部”)
      • 所以,([^,~]*),(不要捕捉逗号!)
    • 如果我们找到~而不是逗号,那就出去吧,然后再回到下一个~
      • 所以,([^,~]*~[^~]*~)

在所有情况下,我们确保捕获足够的数据来重建字符串。

参考

相关问题

答案 1 :(得分:0)

我没有测试过这个,但我会做类似的事情:

string sample = "Blah, blah, blah,~Part One, Part Two~,blah blah";
Regex r = new Regex("(.+)\\~(.+),(.+)\\~(.+)","${1}~${2}${3}~${4}");
r.replaceAll(sample );

我引用了Regular Expressions in Java。在这里,。+匹配一个或多个任何字符。可以找到更多此类模式here

答案 2 :(得分:0)

String text = "Blah, blah, blah,~Part One, Part Two~,blah blah,~Part One, Part Two~,blah blah";
Pattern pattern = Pattern.compile("~[^~]+~");
Matcher matcher =pattern.matcher(text);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
    matcher.appendReplacement(sb, matcher.group(0).replaceAll(",", ""));
}
matcher.appendTail(sb);
text = sb.toString();

答案 3 :(得分:0)

这是一种可以胜任的方法:

public String deleteCharacterBetween(String deleteFrom, String betweenChar, String charToRemove) {
    int nextIndex = 0, index = 0;
    while (true) {
        index = deleteFrom.indexOf(betweenChar, nextIndex);
        nextIndex= deleteFrom.indexOf(betweenChar, index + 1);
        if (nextIndex < 0 || index < 0)
            return deleteFrom;
        String before = deleteFrom.substring(0, index);
        String toEdit = deleteFrom.substring(index, nextIndex);
        String after = deleteFrom.substring(nextIndex);
        toEdit = toEdit.replace(charToRemove, "");
        deleteFrom = before + toEdit + after;
    }
}

您可以这样称呼它:

String a = "Blah, blah, blah,~Part One, Part Two~,blah blahBlah, blah, blah,~Part One, Part Two~,blah blah";
System.out.println(deleteCharacterBetween(a, "~", ","));