簡體   English   中英

如何使用正則表達式刪除括號/括號之間的所有非數字字符?

[英]How to remove all non numeric characters between brackets/parentheses with a regex?

我正在嘗試從字符串中刪除括號和括號之間的所有非數字字符,例如, "hello (a1b2c3) (abc)"將變為"hello 123"

我如何使用正則表達式呢?

根據OP的評論,沒有不平衡或轉義的引號。 請記住,這里是一個單獨的replaceAll方法調用來實現:

String repl = input.replaceAll("(?:\\D(?=[^(]*\\))|\\)\\s*)", "");

//=> hello 123

使用正向先行,我們使用先行\\\\D(?=[^(]*\\\\))找到括號內的所有非數字,然后刪除)其后是交替的可選空格。

正則演示

您可以使用splitreplaceAll實現此目的。

public static void main(String[] args) {
    String s = "hel121lo (a1b2c3) (abc)";
    String[] arr = s.split("\\s+");
    StringJoiner sj = new StringJoiner(" ");
    for (String str : arr) {
        // System.out.println(str);
        if (str.contains("(")) {
            String k = str.replaceAll("\\D|\\(|\\)a", "");
            sj.add(k);
        } else {
            sj.add(str);
        }

    }

    System.out.println(sj.toString());

}

O / P:

hel121lo 123

暫無
暫無

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

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