admin管理员组

文章数量:1292146

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.

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.

Share edited Mar 14, 2018 at 13:00 Cœur 38.7k26 gold badges204 silver badges277 bronze badges asked Aug 13, 2016 at 15:05 GerryGerry 8962 gold badges12 silver badges34 bronze badges 5
  • Did you try at least a few things? – Thomas Ayoub Commented Aug 13, 2016 at 15:07
  • 1 /%(\w+)%/g should work for you. – anubhava Commented Aug 13, 2016 at 15:07
  • To get the array try this "This is a %varA% and %varB% and that one is a %VarC%".match(/%\w+/g) – n0m4d Commented Aug 13, 2016 at 15:09
  • @ThomasAyoub I did. Didn't quite get it. Was using the \w+ in the wrong places. – Gerry Commented Aug 13, 2016 at 15:23
  • Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer :) – Thomas Ayoub Commented Aug 13, 2016 at 16:34
Add a ment  | 

1 Answer 1

Reset to default 8

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));

本文标签: javascriptRegular expression to get all words inside specific patterns ( )Stack Overflow