正则表达式改进

Regular expression improvement

本文关键字:正则表达式      更新时间:2023-09-26

我正在尝试编写正则表达式来捕获数据,但很难完成它。

从数据来看:

Code:Name Another-code:Another name

我需要获取一个数组:

['Code:Name', 'Another-code:Another name']

问题在于,除了空间之外,代码几乎可以是任何东西。

我知道如何在不使用正则表达式的情况下做到这一点,但决定给他们一个机会。

更新:忘了提到元素的数量可以从一到无穷大不等。所以数据:

Code:Name -> ['Code:Name']
Code:Name Code:Name Code:Name -> ['Code:Name', 'Code:Name', 'Code:Name']

也很合适。

只需根据空格拆分输入,后跟一个或多个非空格字符和一个:符号。

> "Code:Name Another-code:Another name".split(/'s(?='S+?:)/)
[ 'Code:Name', 'Another-code:Another name' ]

> "Code:Name Another-code:Another name".split(/'s(?=[^'s:]+:)/)
[ 'Code:Name', 'Another-code:Another name' ]

怎么样:

^('S+:.+?)'s('S+:.+)$

Code:Name在第 1 组中,Another-code:Another name在第 2 组中。

'S+表示一个或多个不是空格的字符。

这是一种不使用正则表达式的方法:

var s = 'Code:Name Another-code:Another name';
if ((pos = s.indexOf(' '))>0) 
   console.log('[' + s.substr(0, pos) + '], [' + s.substr(pos+1) + ']');
//=> [Code:Name], [Another-code:Another name]