簡體   English   中英

Java正則表達式匹配列表中的一個或多個字符

[英]Java Regular Expression match one or more characters in list

我有一些字符串:

  • 總計19xx.100
  • 總計19x..100
  • 總共19..100
  • 總計19x .100

我想將19與(“x”或“。”一次或多次)和100分開。我試圖使用正則表達式:

 (x|\.)+

分組,但它不能匹配上面的所有情況。 哪個正則表達式可以匹配上面的所有情況?

你可以使用正則表達式:

public static Matcher split(String text) {
    Pattern pattern = Pattern.compile("(\\d+)(x*)(\\s*)(\\.*)(\\d+)");
    Matcher matcher = pattern.matcher(text);
    matcher.find();

    return matcher;
}

此正則表達式適用於測試數據:

19xx.100
19x.100
19..100
19x .100

之后matcher.group(1)將返回19matcher.group(5)將返回100

對於您的示例,您可以捕獲2個捕獲組中100和100之前的內容:

(\\d+[x. ]+)(\\d+)

說明

  • 捕獲小組(第1組) (
  • 匹配一個或多個數字\\d+
  • 匹配一次或多次x , . 或空白[x. ]+ [x. ]+使用一個字符類
  • 關閉捕獲組)
  • 在組(組2)中捕獲一個或多個數字(\\d+)

你可以用

(\d+)(\s*[x.][x.\s]*)(\d+)

請參閱正則表達式演示

細節

  • (\\d+) - 第1組:一個或多個數字
  • (\\s*[x.][x.\\s]*) - 第2組:
    • \\s* - 0+空格
    • [x.] - x.
    • [x.\\s]* - 0+字符是x , . 或空白字符
  • (\\d+) - 第3組:一個或多個數字

暫無
暫無

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

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