prime
prime

Reputation: 15594

Regex to match the argument of a function

I need to match the argument of a function with a specific name. (In this case let's say the function name if function)

So basically if there is a occurrence like function(my_argument) in a file, I want to extract the argument my_argument from it. (basically what i need here is to collect all the argument passed to the function() in that file)

So far I came up with a regex

(([;][ ]{0,})|([ ]{1,})|(\n))function[(](([^()]*)*)[)]

But seems it does not catch it if the function(my_argument) is the first line of the file. check example in regex101.com.

Is there any way to capture that instance as well. Or if there are better ways to do this i'm open to suggestions as well, and highly appreciate it.

Upvotes: 1

Views: 1351

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627469

It seems you want

(^|;?[ ]+|\r?\n)function[(]([^()]*)[)]

See the regex demo

Details:

  • (^|;?[ ]+|\r?\n) - Group 1 capturing
    • ^ - start of string
    • | - or
    • ;?[ ]+ - an optional ; followed with 1+ spaces
    • | - or
    • \r?\n - a linebreak (an optional CR followed with LF)
  • function - a literal char sequence
  • [(] - a literal (
  • ([^()]*) - Group 2 capturing 0+ chars other than ( and )
  • [)]- a literal ).

Upvotes: 0

Related Questions