Simeon Mark Fernandes
Simeon Mark Fernandes

Reputation: 107

Regex more than one occurrence of a symbol

My regex is as follows (.*?)add\(\${2,}(.*?)\)

I want this to validate add($arg1, $agr2)

That is to detect more than 1 occurance of '$' within the add function. I want to return all the text before the add function hence i used (.*?) But the {2,} part doesn't seem to work for me.

Upvotes: 0

Views: 104

Answers (1)

The fourth bird
The fourth bird

Reputation: 163477

You can use the capturing group to match as least as possible before add.

Then match a single argument starting with a dollar sign and match 1 or more word characters followed by repeating 1 or more times a comma and again an argument.

Note that (.*?) will also match an empty string.

(.*?)\badd\(\$\w+(?:\h*,\h*\$\w+)+\)

Explanation

  • (.*?) Capture group 1, match any char except a newline 0+ times as least as possible
  • \badd A word boundary, then match add
  • \( Match (
  • \$\w+ match $ and 1+ word characters
  • (?: Non capture group
    • \h*,\h*\$\w+ match a comma between optional horizontal whitespace chars
  • )+ Close group and repeat 1+ times
  • \) Match )

See a regex demo

Upvotes: 1

Related Questions