简体   繁体   中英

Regex to match 7numberdigits followed by “,”

I am trying to match (0 or more)occurrences of 7digit or more numbers followed by "," Below is the regex i am using, but it doesnt help

^(\\d{7,}(?:,\\d{7,})*)$

Sample string - 122343,14435356,123254356,324556,121,45,124325,1343545,1323544 Output - 14435356,123254356,1343545,1323544

The problem is that your sample string doesn't have numbers at the start or end that are seven or more characters long. Simply removing the starting and ending constraints will return the matches you expect:

(\d{7,}(?:\,\d{7,})*)

Returns:

14435356,123254356
1343545,1323544

This can be seen on Regex101 .

Regex : \\b(?:\\d{1,6},|,\\d{1,6}$)\\b|(\\d{7,}) Substitution : $1

Output: 14435356,123254356,1343545,1323544

Regex demo

Java code:

String text = "122343,14435356,123254356,324556,121,45,124325,1343545,1323544";
text = text.replaceAll("\\b(?:\\d{1,6},|,\\d{1,6}$)\\b|(\\d{7,})", "$1");
System.out.print(text); //14435356,123254356,1343545,1323544

An alternative, simple, non-regex solution would be to just split the string by , , and loop through the results and check if greater than 6.

String[] split = s.split(",");
for (String string : split) {
    if (string.length() > 6) {
        System.out.println(string);
    }
}

Or if you like Java8 solutions, convert to a List and filter the stream:

List<String> myList = Arrays.asList(s.split(","));
myList.stream().filter(a -> a.length() > 6).collect(Collectors.toList()).forEach(System.out::println);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM