Java从字符串中替换精确的子字符串

时间:2014-01-28 12:35:52

标签: java regex string str-replace

我有以下字符串:

String str = "6,20,9,10,19,11,5,3,1,2";

我希望将确切的字符串,21,替换为空字符串,从而避免将子字符串,2011,置于替换中。< / p>

我有这段代码:

// assuming that substr = ",2" or "1,"

if(str.startsWith(substr+",")){
    str = str.replace("^"+substr+",$","");
}               
else if(str.contains(","+substr+",")){
    str = str.replace("^"+substr+",$","");
}   
else if(str.endsWith(","+substr)){
    str = str.replace("^,"+substr+"$","");
}

但似乎我对正则表达式错了。我应该使用哪个正则表达式来解决它?

2 个答案:

答案 0 :(得分:2)

我的回答是:“你想要实现什么?”

如果您尝试过滤我会去String.split(","),然后过滤字符串数组中生成的项目。最终我会加入它们(如果你不受运行时约束)。

类似(未经测试):

String[] splits = myString.split(",");
// ... manipulate splits (filter into a list if you want...)
StringUtils.join(splits, ", "); // possibly replace with array from filtered list
  • 拆分可以由已过滤的列表toArray
  • 替换

按照你的方式解决它可能会很棘手。当您尝试匹配项目时,您将无法匹配其邻居。您需要做的是匹配聚合。

这只是一个开始(未经测试,基于this):

    List<String> matches = new ArrayList<String>();
    Matcher m = Pattern.compile("(^[12],|,[12],|[12]$)").matcher("1,6,20,9,10,19,11,5,3,1,2");
    if (m.find()) {
        do {
            System.out.println("Matched "+m.group());
            matches.add(m.group());
        } while (m.find(m.start()+1));
    }

    for (String match : matches){
        System.out.println(match);
    }

您可以尝试两种方式分析运行时间,也可以稍后扩展我的答案: - )

答案 1 :(得分:0)

我认为问题是“如何从列表中删除值”,但只有完全值(例如2不是12,13而不是413),并缩短列表,即删除前面或后面的逗号(如果有),但不能同时删除。

简答:

String x = Pattern.quote(textToRemove);
Pattern p = Pattern.compile("^"+x+"$|^"+x+",|,"+x+"$|,"+x+"(?=,)");
String output = p.matcher(input).replaceAll(""); // or replaceFirst

示例:

Input:       "6,20,9,10,19,101,5,3,1,2"
Remove "2":  "6,20,9,10,19,101,5,3,1"   -- last value, don't remove 20
Remove "20": "6,9,10,19,101,5,3,1,2"    -- middle value
Remove "1":  "6,20,9,10,19,101,5,3,2"   -- don't remove 10, 19, or 101
Remove "10": "6,20,9,19,101,5,3,1,2"    -- don't remove 101
Remove "6":  "20,9,10,19,101,5,3,1,2"   -- first value
Remove "77": "6,20,9,10,19,101,5,3,1,2" -- nothing removed

Input:       "6"
Remove "6":  ""                         -- only value

代码:

private static void test(String input, String textToRemove) {
    String rmv = Pattern.quote(textToRemove);
    Pattern p = Pattern.compile("^" + rmv + "$" +     // matches only value
                               "|^" + rmv + "," +     // matches first value + ','
                               "|," + rmv + "$" +     // matches ',' + last value
                               "|," + rmv + "(?=,)"); // matches ',' + middle value (+ ',')
    String output = p.matcher(input).replaceAll(""); // or replaceFirst
    System.out.printf("Remove %-4s from %-26s: %s%n",
                      '"' + textToRemove + '"',
                      '"' + input + '"',
                      '"' + output + '"');
}

测试:

public static void main(String[] args) throws Exception {
    //
    test("6,20,9,10,19,101,5,3,1,2", "2" );
    test("6,20,9,10,19,101,5,3,1,2", "20");
    test("6,20,9,10,19,101,5,3,1,2", "1" );
    test("6,20,9,10,19,101,5,3,1,2", "10");
    test("6,20,9,10,19,101,5,3,1,2", "6" );
    test("6,20,9,10,19,101,5,3,1,2", "77");
    test("6"                       , "6" );
}

输出:

Remove "2"  from "6,20,9,10,19,101,5,3,1,2": "6,20,9,10,19,101,5,3,1"
Remove "20" from "6,20,9,10,19,101,5,3,1,2": "6,9,10,19,101,5,3,1,2"
Remove "1"  from "6,20,9,10,19,101,5,3,1,2": "6,20,9,10,19,101,5,3,2"
Remove "10" from "6,20,9,10,19,101,5,3,1,2": "6,20,9,19,101,5,3,1,2"
Remove "6"  from "6,20,9,10,19,101,5,3,1,2": "20,9,10,19,101,5,3,1,2"
Remove "77" from "6,20,9,10,19,101,5,3,1,2": "6,20,9,10,19,101,5,3,1,2"
Remove "6"  from "6"                       : ""