gpt4 book ai didi

java - 正则表达式匹配用多个逗号分隔的数字

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:42 24 4
gpt4 key购买 nike

我正在使用正则表达式识别模式。

我的用例是查找以下格式的字符串

100,253,2586,3654

这是我试过的

(\d+\,+\d+\,*)+

但它似乎不能正常工作。

帮我解决问题。

进一步评论:
模式应识别

1. Any combination of numbers separated by a comma  (eg: 123,465,798)  
2. shouldn't begin or end with comma (eg: ,123,46 )
3. Decimals (eg: 123,465.2324)

最佳答案

尝试这样的事情:

public static void main(String[] args) {
String s = "100,253,2586,3654";
System.out.println(s.matches("((?<!^,)\\d+(,(?!$)|$))+"));
}

编辑:正则表达式解释。

((?<!^,)\\d+(,(?!$)|$))+") ==>

\\d+ ==> matches one or more digits.

(?<!^,) ==> Negative look-behind. Checks if String doesn't start with a ",".

(,(?!$)|$))+") ==> checks digits are - either followed by a comma and NOT followed by end of String OR followed by end of String.

这将

  1. Prevent a comma at the beginning.
  2. prevent comma at the end.
  3. multiple commas

关于java - 正则表达式匹配用多个逗号分隔的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34034857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com