正则表达式改进

时间:2014-12-05 17:41:02

标签: javascript regex

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

来自数据:

Code:Name Another-code:Another name

我需要一个数组:

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

问题是代码几乎可以是任何空间。

我知道怎么做而不使用正则表达式,但决定给他们一个机会。

更新:忘记提及元素数量可以从1到无穷大。所以数据:

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

也适合。

3 个答案:

答案 0 :(得分:2)

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

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

OR

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

答案 1 :(得分:1)

怎么样:

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

Code:Name位于第1组,Another-code:Another name位于第2组。

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

答案 2 :(得分:0)

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

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] 
相关问题