正则表达式来解析类似jQuery-selector的字符串

Nee*_*ngh 3 javascript regex

text = '#container a.filter(.top).filter(.bottom).filter(.middle)';

regex = /(.*?)\.filter\((.*?)\)/;

matches = text.match(regex);

log(matches);
// matches[1] is '#container a'
//matchss[2] is '.top'
Run Code Online (Sandbox Code Playgroud)

我期待捕获

matches[1] is '#container a'
matches[2] is '.top'
matches[3] is '.bottom'
matches[4] is '.middle'
Run Code Online (Sandbox Code Playgroud)

一种解决方案是将字符串拆分为#container a 并休息.然后休息并执行recursive exec以获取item()内的项目.

更新:我发布了一个有效的解决方案.但是我正在寻找更好的解决方案.不喜欢拆分字符串然后处理的想法这是一个有效的解决方案.

matches = [];

var text = '#container a.filter(.top).filter(.bottom).filter(.middle)';
var regex = /(.*?)\.filter\((.*?)\)/;
var match = regex.exec(text);
firstPart = text.substring(match.index,match[1].length);
rest = text.substring(matchLength, text.length);

matches.push(firstPart);

regex = /\.filter\((.*?)\)/g;
while ((match = regex.exec(rest)) != null) {
  matches.push(match[1]);
}
log(matches);
Run Code Online (Sandbox Code Playgroud)

寻找更好的解决方案.

Bar*_*ers 5

这将匹配您发布的单个示例:

<html>
  <body>
    <script type="text/javascript">
      text = '#container a.filter(.top).filter(.bottom).filter(.middle)';
      matches = text.match(/^[^.]*|\.[^.)]*(?=\))/g);
      document.write(matches);
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

产生:

#container a,.top,.bottom,.middle 
Run Code Online (Sandbox Code Playgroud)

编辑

这是一个简短的解释:

^         # match the beginning of the input
[^.]*     # match any character other than '.' and repeat it zero or more times
          #
|         # OR
          #
\.        # match the character '.'
[^.)]*    # match any character other than '.' and ')' and repeat it zero or more times
(?=       # start positive look ahead
  \)      #   match the character ')'
)         # end positive look ahead
Run Code Online (Sandbox Code Playgroud)

编辑第二部分

正则表达式查找两种类型的字符序列:

  1. 一个或多个字符从字符串的开头到第一个.,正则表达式:^[^.]*
  2. 或者它匹配的字符序列开头的.,然后比其他零个或多个字符.),\.[^.)]*必须)它的未来:(?=\)).最后一个要求导致.filter 匹配.