Shafeeque
Shafeeque

Reputation: 2069

RegEx to extract parenthesis and function name

Somebody help me to write RegEx for the following cases

This is I tried so far

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

Upvotes: 2

Views: 512

Answers (4)

user663031
user663031

Reputation:

I would attempt to handle this with Proxy, as follows:

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]
);

This works properly in node, but not in the Chrome devtools console, because the latter apparently tries to invoke the get on each element when serializing to the console using console.log.

Node output:

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

The basic idea here is to create a function proxy, which when invoked (apply) returns the ['somestring', arg] array, but also wrap a proxy around that which traps property accesses (get) such as [10], and return ['somestring', arg, 10] in that case.

Upvotes: 0

guest271314
guest271314

Reputation: 1

You can negate (,), [, ] from matches

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

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

Upvotes: 2

MattMS
MattMS

Reputation: 1156

You just needed to exclude the closing brackets:

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

This will break if you have a string like the following though:

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

Upvotes: 1

smnbbrv
smnbbrv

Reputation: 24551

That could work:

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]];
}));

Upvotes: 2

Related Questions