簡體   English   中英

Java從字符串中替換精確的子字符串

[英]Java replace exact substring from string

我有以下字符串:

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

並且我想將確切的字符串,21,替換為空字符串,避免將子字符串,2011,包含在替換中。

我有這個代碼:

// 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+"$","");
}

但似乎我對正則表達式錯了。 我應該使用哪個正則表達式來解決它?

我的回答是:“你想要實現什么?”

如果你試圖過濾我會去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替換

以你的方式解決它可能會很棘手。 當您嘗試匹配項目時,您將無法匹配其鄰居。 您需要做的是匹配聚合。

這只是一個開始( 未經測試 ,基於 ):

    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);
    }

您可以嘗試兩種方式運行時間,也可以稍后擴展我的答案:-)

我相信問題是“如何從列表中刪除值”,但只有確切的值(例如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"                       : ""

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM