RegEx提取括号和函数名称

时间:2017-01-21 07:39:08

标签: javascript regex

有人帮助我为以下情况编写RegEx

  • somestring()=> ['somestring']
  • somestring()[10] => ['somestring','',10]
  • somestring(' argString')=> ['somestring', 'argString']
  • somestring(' argString')[10] => ['somestring', 'argString',10]
  • somestring({prop1:' v1',prop2:' v2'})=> ['somestring', {prop1:'v1',prop2:'v2'}]

  • somestring({prop1:' v1',prop2:' v2'})[100] => ['somestring', {prop1:'v1',prop2:'v2'},100]

这是我到目前为止尝试的

var regExp = /\b[^()]+\((.*)\)+\[(.*?)]/;
var matches = regExp.exec('somestring()[10]');

4 个答案:

答案 0 :(得分:2)

这可行:

var input = ['somestring()', 'somestring()[10]', "somestring('argString')", "somestring('argString')[10]", "somestring({prop1:'v1',prop2:'v2'})", "somestring({prop1:'v1',prop2:'v2'})[100]"];

console.log(input.map(function(v) {
  let result = v.match(/(.*)\((.*)\)(\[([^\]]*)\])?/);

  return [result[1], result[2], result[4]];
}));

答案 1 :(得分:2)

您可以从匹配项中否定()[]

let re = /[^()\[\]]+/g;

let res = "somestring({prop1:'v1',prop2:'v2'})[100]".match(re);

答案 2 :(得分:1)

您只需要排除右括号:

var regExp = /\b[^()]+\(([^)]*)\)(\[[^\]]*\])?/;

如果你有一个像下面这样的字符串,这将会中断:

somestring({myKey: myFunc()})[myArray[0]]

答案 3 :(得分:0)

我会尝试使用Proxy处理此问题,如下所示:

const somestring = new Proxy(() => {}, {
  apply(target, thisArg, [arg = '']) {
    return new Proxy(['somestring', arg], {
      get(target, prop) {
        if (!isNaN(String(prop))) return [...target, prop];
        return target[prop];
      }
    });
  }
});

console.log(
  somestring(),
  somestring()[10],
  somestring('argString'),
  somestring('argString')[10],
  somestring({prop1:'v1',prop2:'v2'}),
  somestring({prop1:'v1',prop2:'v2'})[100]
);

这在节点中正常工作,但在Chrome devtools控制台中没有,因为当使用get序列化到控制台时,后者显然会尝试在每个元素上调用console.log

节点输出:

[ 'somestring', '' ] 
[ 'somestring', '', '10' ] 
[ 'somestring', 'argString' ] 
[ 'somestring', 'argString', '10' ] 
[ 'somestring', { prop1: 'v1', prop2: 'v2' } ] 
[ 'somestring', { prop1: 'v1', prop2: 'v2' }, '100' ]

这里的基本思想是创建一个函数代理,在调用时(apply)返回['somestring', arg]数组,但也包围一个陷阱属性访问的代理(get )例如[10],并在这种情况下返回['somestring', arg, 10]