3

给定字符串:

有趣的 -> A_gre$" [ "at -> 看起来 ->很棒/*54[ [有趣的" -> [ " -> [很棒的 -> yolo] -> 看起来]][很棒] -> a2afg34423*/- ->哟洛“-> [”

拆分为数组:

  1. 有趣的
  2. A_gre$' ['在
  3. 看起来
  4. 很棒/*54[[有趣的'->['->[很棒->yolo]->看起来]][很棒]
  5. a2afg34423*/-
  6. 哟洛'-> ['

正则表达式解决方案??!?

基本上,如果括号周围有引号,请避免括号作为打开/关闭分隔符的功能,否则请确保打开括号和关闭括号之间的文本无效。我将如何使用正则表达式实现这一目标?

我的解析器解决方案 测试

var s = "funny -> A_gre$' [ 'at -> looks -> great/\*54[ [funny ' -> [ ' ->"
        + "[great -> yolo] -> looks]][great] -> a2afg34423*/- -> yolo' -> [ '",
    p = 0,
    z = [0],
    q = 0,
    x = s.split('');

//Looking for \" not \'
for(var i = 0; i< x.length; i++){
   var b = x[i],
       c = x[i + 1],
       q = b == "'" ? ++q : q,
       p =  !(q % 2) ? b == '[' ? ++p : b == ']' ? --p : p : p;

   if(b == '-' && c == '>' && !p && !(q % 2))
       z.push(i + 2);
   if(i == x.length - 1){
       z.push(x.length); x = [];
       for(var u = 0; u < z.length; u++)
         z[u + 1] !== undefined ?
              x.push(s.substring(z[u], z[u + 2] !== undefined ?
                      z[u + 1]-2 : z[u + 1]).trim()) : 0;
    }
}

console.log(x)

输出:

->>> [
      "funny", 
      "A_gre$' [ 'at", 
      "looks", 
      "great/*54[ [funny ' -> [ ' -> [great -> yolo] -> looks]][great]", 
      "a2afg34423*/-", 
      "yolo' -> [ '"
     ]
4

1 回答 1

2

试试这个模式:

([^\s\[\"]*\[[^\]]+\])\S*|([^\s\[\"]*\"[^\"]+\")\S*|(\w\S*)

使用正则表达式查看它匹配的内容。它由三部分组成。其中之一的描述如下:

([^\s\[\"]*\[[^\]]+\])\S*

表达式读取非空格、非引号和非括号字符,直到它到达一个左括号,然后读取括号内容直到它到达右括号,然后读取它之后出现的任何非空格字符。这是括号匹配部分的更详细描述:

\[         : opening bracket character
[          : regex syntax for starting a set definition
   ^       : It's a negative set, i.e., set of characters which are NOT:
   \]      : closing bracket character
]+         : regex syntax for ending a set definition and the + operator for matching 1 or more occurrences
\]         : closing bracket character

另一部分处理引号,另一部分匹配没有括号和引号的单词。

以下代码显示了如何查看匹配项以及如何提取它们:

var input = 'funny -> A_gre$" [ "at -> 看起来 -> 很棒/ 54[ [funny " -> [ " -> [great -> yolo] -> 看起来]][great] -> a2afg34423 /- -> yolo" -> ["'

var regexp = /([^\s\[\"]*\[[^\]]+\])\S*|([^\s\[\"]*\"[^\"]+\")\S*|(\w\S*)/g;

var result = input.match(regexp)
console.log("Array of matches are:");
console.log(result);

var results = regexp.exec(input);
while(results != null) {
    console.log("index: " + results.index + " found: " + results[0]);
    results = regexp.exec(input);
} 

这可以在这里看到:http: //jsfiddle.net/LXqch/1/

于 2013-02-27T05:40:24.857 回答