I am trying to match a function call using Regex but is not giving on big JS file where nested calls of the same function are inside. For example below is the code in JS file
abc('hello', function(){
abc('hello1', function(){
abc('hello2', function() {
// Does some!
});
});
});
And I want to match only first call to identify the first parameter. The end result I am looking for is hello
. So doing like below to match first call
.replace(/(?:\r\n|\r|\n)/g, '').match(/abc\s*[^\"\']*\"([^\"\']*)\"/);
Any suggestions please?
I am trying to match a function call using Regex but is not giving on big JS file where nested calls of the same function are inside. For example below is the code in JS file
abc('hello', function(){
abc('hello1', function(){
abc('hello2', function() {
// Does some!
});
});
});
And I want to match only first call to identify the first parameter. The end result I am looking for is hello
. So doing like below to match first call
.replace(/(?:\r\n|\r|\n)/g, '').match(/abc\s*[^\"\']*\"([^\"\']*)\"/);
Any suggestions please?
Share Improve this question asked Jan 27, 2015 at 9:32 redVredV 6841 gold badge9 silver badges27 bronze badges 2- 1 Why down votes? Mr. Downvoter could you please behave yourself to give explanation for downvote? – redV Commented Jan 27, 2015 at 9:35
- 9 I didn't downvote, but it is generally considered a bad idea to use regexes for this kind of job. Particularly because of the nested/recursive nature of the input data. You are better off looking for a library that interprets the JavaScript as exactly that, JavaScript (rather than a huge string) and let's you do what you need to do. – asontu Commented Jan 27, 2015 at 10:32
1 Answer
Reset to default 9 +50You can use a JS parser like Esprima to do this. This would be the correct and reliable solution rather than a magical regex, in my opinion. Regex's are often hard to maintain and often fail for edge cases. They are very useful in some cases, but this isn't one of them.
To try out Esprima, use this tool:
Esprima Demo
And input:
abc('hello', function(){
abc('hello1', function(){
abc('hello2', function() {
/* ... */
});
});
});
abc('hello3', function(){
abc('hello4', function(){
abc('hello5', function() {
/* ... */
});
});
});
Then filter the returned JSON to find only the first "level" functions and their first argument:
JSON.body.filter(function(token) {
return token.type === 'ExpressionStatement' && token.expression.type ===
'CallExpression' && token.expression.callee.name === "abc"
}).map(function(funcToken) {
return funcToken.expression.arguments[0].value
})
Which returns, in the example's case:
["hello", "hello3"]
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745106208a4611570.html
评论列表(0条)