例如,我有一个字符串包含:'2014-12 to 1251255, 123123'
,我想获取2014-12
, 1251255
和 123123
。这个是正确的:
> '2014-12 to 1251255, 123123'.split( /\s*,\s*|\s*to\s*/ );
[ '2014-12', '1251255', '123123' ]
但是有比上面更短的正则表达式
吗?
我当然尝试过:
> '2014-12 to 1251255, 123123'.split( /\s*(,|to)\s*/ );
[ '2014-12', 'to', '1251255', ',', '123123' ]
> '2014-12 to 1251255, 123123'.split( /\s*,|to\s*/ );
[ '2014-12 ', '1251255', ' 123123' ]
> '2014-12 to 1251255, 123123'.split( /\s*[,|to]\s*/ );
[ '2014-12', '', '1251255', '123123' ]
> '2014-12 to 1251255, 123123'.split( /\s*[,|(to)]\s*/ );
[ '2014-12', '', '1251255', '123123' ]
最佳答案
只需使用匹配功能匹配一个或多个数字或连字符。
> '2014-12 to 1251255, 123123'.match(/[\d-]+/g)
[ '2014-12', '1251255', '123123' ]
或者
> '2014-12 to 1251255, 123123'.match(/\d+(?:-\d+)?/g)
[ '2014-12', '1251255', '123123' ]
关于javascript - 更短的正则表达式可按 2 个条件分割,外部有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29294120/