简体   繁体   中英

Regex to allow one or two digits followed by commas (spaces are allowed too)

I'm trying to implement the regex described on the title...here's what i have so far:

"(^\\d{1,2})+(,\\d{1,2})*$"

It works when my input is like this:

1,2,3,4,5,6,7 and so goes on

But i'd like to allow the user to add white spaces as he/she wants:

1 ,     2,3,4    ,5

I know it's a bit weird but it's a flexibility i'd like to give to the final user. How can i acomplish this?

EDIT: I forgot to mention that the spaces are only allowed before or after the one or two digits;
EDIT2: I also forgot to mention that after the comma, can have white spaces too.

I would add optional whitespace in a positive lookahead, as such:

String input = "1, 2 , 3, 45 , 67,89";
//                           | 1 or 2 digits
//                           |       | start positive lookahead
//                           |       |  | optional whitespace
//                           |       |  |   | comma
//                           |       |  |   || or
//                           |       |  |   ||| end of input
Pattern p = Pattern.compile("\\d{1,2}(?=\\s*,|$)");
Matcher m = p.matcher(input);
while (m.find()) {
   System.out.println(m.group());
}

Output

1
2 
3
45 
67
89

Replace your ', ' with [, ]+

eg

[0-9]+([ ,]+[0-9]+)*

使用: \\\\d{1,2}(?=\\\\s*,*) 。这将匹配您的字符串

我认为这是一种可行的详细方法:

"(\\\\d{1,2}\\\\s*,\\\\s*)*"

As you know

^(\\d{1,2})+(,\\d{1,2})*$ 

works for

1,2,3,4,5,6,7

If you want to let , be surrounded by zero or more spaces you can write it as \\\\s*,\\\\s* . So to let regex match something like

1 ,     2,3,4    ,5

all you need to do is change

^(\\d{1,2})+(,\\d{1,2})*$ 

to

^(\\d{1,2})+(\\s*,\\s*\\d{1,2})*$ 
//           ^^^^^^^^^ - part changed

If you would also like to add spaces before and after your entire input also surround your regex with \\\\s* like

^\\s*(\\d{1,2})+(\\s*,\\s*\\d{1,2})*\\s*$ 

Firstly, I would change

"(^\\d{1,2})+(,\\d{1,2})*$"

to

"^\\d{1,2}(,\\d{1,2})*$"

as that first bracket group won't be repeated, and then throw in a bunch of spaces:

"^\\s*\\d{1,2}\\s*(,\\s*\\d{1,2}\\s*)*$"

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