验证以句点分隔的数字regex



我有一个棘手的正则表达式。

  • 数字由句点分隔
  • 最多可以有4个周期。在每个周期之间可以有0到4个数字

有效表达式包括

....
...
..
.
.1234.1234
..1234.1234.1234
1234.1234.1234.1234.1234 (this is the max string)
1234.1234
1234....1234
1234.1234.1234

无效字符串包括以下

12345 (too many digits example)
..1234...1234 (this is 5 periods)
1234.12345 (too many digits example)

提前感谢

我不认为这特别棘手。。。只需重复一组句点+数字:

^d{0,4}(.d{0,4}){0,4}$

编辑:使用正确的语法效果更好。这是给btw的什么?

编辑2:根据您的正则表达式风格,您可能需要^$

/^d{0,4}(?!d)(?:.?d{0,4}(?!d)){0,4}$/

在JS:中测试

var r = /^d{0,4}(?!d)(?:.?d{0,4}(?!d)){0,4}$/;
r.test('....'); // true
r.test('...'); // true
r.test('..'); // true
r.test('.'); // true
r.test('.1234.1234'); // true
r.test('..1234.1234.1234'); // true
r.test('1234.1234.1234.1234.1234'); // true
r.test('1234.1234'); // true
r.test('1234....1234'); // true
r.test('1234.1234.1234'); // true
r.test('12345'); // false
r.test('..1234...1234'); // false
r.test('1234.12345'); // false

最新更新