英文:
Regex for numbers between 1-31 and optional commas between numbers
问题
我不太擅长正则表达式,也许这对于你们正则表达式专家来说很容易!
基本上,我需要为用户提供在1到31之间输入数字的选项(不带任何尾随零),并且可以在它们之间选择使用逗号(仅限一个)。
有效:
- 1
- 1,22,31
无效:
- A
- 31,33,333
- 2,,
- 1,2.,3%
- 0,1,2,3
到目前为止,我已经尝试过:
^([1-9]|[12]\d|3[0-1]),?\d+$
但我认为它已经开始出错了!
英文:
I'm not very good with regex, maybe this is an easy one for you regex experts out there!
Basically I need the option for a user to enter a number between 1 and 31 (without any trailing zeroes) with optional commas (1 comma only) between them e.g.
Valid:
- 1
- 1,22,31
Invalid:
- A
- 31,33,333
- 2,,
- 1,2.,3%
- 0,1,2,3
So far I've tried:
^([1-9]|[12]\d|3[0-1]),?\d+$
but it's already starting to go wrong I think!
答案1
得分: 2
这是你想要的正则表达式:
^(?:[1-9]|[12]\d|3[0-1])(?:,(?:[1-9]|[12]\d|3[0-1]))*$
英文:
Is that what you want:
^(?:[1-9]|[12]\d|3[0-1])(?:,(?:[1-9]|[12]\d|3[0-1]))*$
答案2
得分: 1
你的正则表达式几乎没问题,除了最后的 \d+
部分,你应该将它完全包含在一个群组内,并选择一个量词。尝试使用这个正则表达式代替:
^(?:(?:[12]\d|3[01]|[1-9]),?\b)+$
查看在线演示。
英文:
You are almost fine with your regex except that final \d+
and you should enclose it entirely within a cluster and choose a quantifier for it. Try this instead:
^(?:(?:[12]\d|3[01]|[1-9]),?\b)+$
See live demo here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论