Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to get all words inside specific patterns (% %)

All I want is this:

The sentences will have some words within % % and I want to extract all of them.

For e.g.

"This is a %varA% and %varB% and that one is a %VarC%"

and when I run it through the Javascript exec I'd like to get %varA%, %varB%, and %varC% in an array.

What would the pattern be? I've tried a number of iterations and none of them gets me each word separately. VarA and VarB etc. will all be words with just a-Z and 0-9, no special characters.

like image 213
Gerry Avatar asked Aug 04 '26 17:08

Gerry


1 Answers

Use String match with /%(\w+)%/g regular expression

Explanation for /%(\w+)%/g

  • % matches the character % literally
  • 1st Capturing group (\w+)
    • \w+ match any word character [a-zA-Z0-9_]
      • Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
  • % matches the character % literally
  • g modifier: global. All matches (don't return on first match)

var string = 'this is a %varA% and %varB% and %varC%';

var regExp = /%(\w+)%/g;

document.write(string.match(regExp));
like image 117
j3ff Avatar answered Aug 07 '26 06:08

j3ff