Wednesday, 23 March 2016

Regex to find function call php



I need the regex to find function calls in strings in php, I have tried to search here on stackoverflow but none of the ones i've tried worked.



this pattern: ^.*([\w][\(].*[\)])



This will match: functionone(fgfg) but also functionone(fgfg) dhgfghfgh functiontwo() as one match. Not 2 separate matches (as in functionone(fgfg) and functiontwo().



I don't know how to write it but I think this is what I need.
1. Any string, followed by (
2. Any string followed by )



And then it should stop, not continue. Any regex-gurus that can help me out?


Answer



I see 5 issues with your regex




  1. If you want to match 2 functions in the same row, don't use the anchor ^, this will anchor the regex to the start of the string.


  2. You then don't need .* at the start maybe more something like \w+ (I am not sure what the spec of a function name in PHP is)


  3. if there is only one entry in a character class (and its not a negated one), you don't need the character class


  4. The quantifier between the brackets needs to be a lazy one (followed by a ?). So after this 4 points your regex would look something like



    \w+\(.*?\)

  5. Is a regex really the right tool for this job?



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...