我想匹配数字,但我需要遵循一些规则。
数字可能(或可能不)以符号[+ - ]开头。
如果数字以0开头,则不能跟随任何内容。
但是,如果它本身是0,它应该匹配。如何忽略使用正则表达式以0(零)开头的数字?
我想出了下面的正则表达式:
[+-]*[1-9]\d*|[+-]*[0](?!\w)
但它不完全工作,我需要:
01 (matches 1, should match nothing)
9,000 (matches 9 and last 0, should match 9 only)
+0152 (matches 152, should match nothing)
-1200 (matches -1200, working as intended)
+0 (matches +0, working as intended)
@WiktorStribiżew为什么不是'[+ - ]?'?我们是否期望多重加减? –
我正在学习正则表达式,我用'*'表示'0或1',现在我看到它是'0或许多'。你说得对,我应该用'?'! –