Jay Bienvenu
Jay Bienvenu

Reputation: 3293

Regular expression for function call containing two arguments

In many languages, a function call consists of a slug followed by any number of arguments surrounded by parentheses, like so:

my_function(); // no arguments
my_function(one_argument);
my_function(first_argument,second_argument);
my_function(first_argument,second_argument,third_argument);

What regular expression will match exactly the case with two arguments (the third case in the pseudocode above)?

The "obvious answer" would be something like \w+\([^)]+,[^)]+\). However, the special meaning of the parentheses breaks this expression.

Upvotes: 0

Views: 311

Answers (2)

zer00ne
zer00ne

Reputation: 43853

Try:

/\w+\([a-zA-Z_$][\w$]*, ?[a-zA-Z_$][\w$]*\);/g

RegEx101

Segment Description
\w+\([a-zA-Z_$]
Any letter, number, or underscore one or more times, then a literal (, then any letter, underscore, or dollar sign
[\w$]*, ?
Any letter, number, underscore, or dollar sign zero or more times, then a literal ,, then a single space or nothing
[a-zA-Z_$][\w$]*\);
Any letter, underscore, or dollar sign, then any letter, number, underscore, or dollar sign zero or more times, then a literal );

Note that each parameter is [a-zA-Z_$][\w$]* which follows the rules for naming a JavaScript variable:

  • May consist of any letter, number, underscore, or dollar sign.
  • Must start with a letter, underscore, or dollar sign.

For a PHP variable: $[a-zA-Z_]\w*

For a Python variable: [a-zA-Z][a-zA-Z_]*

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163207

You might write the pattern like this using a negated character class and also omit matching the comma:

\w+\([^,)]+,[^,)]+\);

Explanation

  • \w+ Match 1+ word chars
  • \( Match `(1
  • [^,)]+ Match 1+ chars other than , and )
  • , Match the single comma
  • [^,)]+ Match 1+ chars other than , and )
  • \); Match );

Regex demo

Upvotes: 1

Related Questions