简体   繁体   English

正则表达式允许一两位数字后跟逗号(也允许空格)

[英]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. EDIT2:我也忘记提及逗号后,也可以有空格。

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* . 如果您想让,零个或多个空格所包围,您可以把它写成\\\\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*将正则表达式括起来,例如

^\\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*)*$"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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