问题
我想实现它匹配[0-9]:[0-9]
或[0-9].[0-9]
或[0-9]
或[0-9]:
或[0-9].
正则表达式
我曾尝试
/^\d?(\d+)?((\.|\:|\d)$|(\.|\:|\d)(\d+)?\d$)/
这是我的满足此条件正则表达式。
我的优化代码
\d+[\.:]*\d*
但是,这是接受2:2:
。其实这不应该。不能够解决这个问题。
您\d+[\.:]*\d*
是不固定和模式匹配的部分子相匹配。此外,它匹配11.....:::::
像字符串作为[.:]*
匹配0+ .
或:
字符。
您可以使用
^\d+(?:[.:]\d*)?$
细节
^
- 字符串的开始\d+
- 1+数字(?:
- 非捕获组匹配的开始
[.:]
- 一个.
或:
\d*
- 0+位数)?
- 1或0次$
- 字符串的结尾。如何\d([:.]\d?)?
?这应该处理你提到的所有案件。
或者,如果你想接受每个号码多于一个数字\d+([:.]\d*?)?
。
为了只匹配精确,如果简单地启动和^
添加$
正则表达式的结束。例:
const regex = /^\d+([:.]\d*?)?$/
console.log(regex.test('2'))
console.log(regex.test('2:'))
console.log(regex.test('2.'))
console.log(regex.test('2:3'))
console.log(regex.test('2.3'))
console.log(regex.test('12:23'))
console.log(regex.test('23.34'))
console.log(regex.test('2:3:4'))
console.log(regex.test('2.3.4'))
2:2:是没有得到完全匹配,只有子2:2
为了避免这种情况,只需使用锚^和$就像你在原来的模式中使用。下面是一个工作正则表达式样品使用正则表达式的优化与锚加 - /^\d+[.:]?\d*$/
,这里是它https://regexr.com/47msc链接