使用 Regex 和 JS 迭代字符串

Iterate a string with Regex and JS

我有一组结构化数据到一个字符串中,我需要通过 Javascript 中的常规 espression 对其进行迭代。

这是数据示例:

|KEY1|VALUE 1 |KEY2| VALUE 2 |KEY3| OTHER VALUE WITH ANY CHARACTER LIKE SPACES, |PIPES| AND WHAT YOU WANT |KEY4| VALUE4

我需要解析它们并创建一个像这样的结构化对象(或数组):

myObject.KEY1 = "VALUE 1"
myObject.KEY2 = "VALUE 2"
myObject.KEY3 = "OTHER VALUE WITH ANY CHARACTER LIKE SPACES, AND WHAT YOU WANT"
myObject.KEY4 = "VALUE4"

我用那个简单的正则表达式得到了键:[|](.+?)[|]但我不知道如何遍历它们和它们各自的值。

我假设一个键是由表达式 \|KEY[0-9]+\| 定义的,因为这是包含 |KEY1||KEY4| 同时排除 |PIPES| 的最简单方法].

如果您的目标是使用循环和正则表达式匹配,而不是单个复杂的正则表达式或使用 indexOf() 等函数进行实际解析,那么这可以通过负前瞻来完成.

var x = "|KEY1|VALUE 1 |KEY2| VALUE 2 |KEY3| OTHER VALUE WITH ANY CHARACTER LIKE SPACES, |PIPES| AND WHAT YOU WANT |KEY4| VALUE4";

var map = {};

while(x.length > 0) {
    var key = x.match(/\|KEY[0-9]+\|/)[0];
    x = x.substr(key.length);
    var value = x.match(/(.(?!\|KEY[0-9]+\|))*/)[0];
    x = x.substr(value.length);
    map[key] = value;
}

alert(JSON.stringify(map, null, 4));

http://jsfiddle.net/eyL7yhwr/

这样就可以了。

//using regex
var keyString = "|KEY1|VALUE 1 |KEY2| VALUE 2 |KEY3| OTHER VALUE WITH ANY CHARACTER LIKE SPACES, |PIPES| AND WHAT YOU WANT |KEY4| VALUE4"
var cases = keyString.match(/[^|]+/g)
var myObject = {};
if (cases.length > 0)
  {
     for (var i = 0; i < cases.length; i += 2)
     {
       myObject[cases[i].toString()] = cases[i+1].trim();
     }
  }
  
  document.write(JSON.stringify(myObject));

你可以这样做:

var s = "|KEY1|VALUE 1 |KEY2| VALUE 2 |KEY3| OTHER VALUE WITH ANY CHARACTER LIKE SPACES, |PIPES| AND WHAT YOU WANT |KEY4| VALUE4";

s.match(/\|(KEY\d+)\|.*?(?=\|KEY\d|$)/g).reduce(function (res, v) { 
  var match = v.match(/(KEY\d+)\|(.*?)\s*$/);
  res[match[1]] = match[2];
  return res;
}, {})

另一个更简单的解决方案:

var s = "|KEY1|VALUE 1 |KEY2| VALUE 2 |KEY3| OTHER VALUE WITH ANY CHARACTER LIKE SPACES, |PIPES| AND WHAT YOU WANT |KEY4| VALUE4";

var v, res = {}, match = s.match(/\s*\|KEY\d+\|\s*|.+?(?=\s*\|KEY\d|$)/g);
while(v = match.shift()) 
  res[v.replace(/^[\s|]*|[\s|]*$/g, '')] = match.shift();

exec/[^|]+/g 这样的东西会给你一个很好的数组。

var str = "|KEY1|VALUE 1 |KEY2| VALUE 2 |KEY3| OTHER VALUE WITH ANY CHARACTER LIKE SPACES, |PIPES| AND WHAT YOU WANT |KEY4| VALUE4";

var re = /[^|]+/g;

var arr = [];

while ((arr = re.exec(str)) !== null){
  console.log(arr[0].trim());
}

fiddle

它比这里的其他一些正则表达式简单一些,而且我认为它的可读性更高一些。我也用了trim(),如果你想在IE9之前支持,你必须使用the polyfill