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
1 Answer
Reset to default 8Use 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]
- Quantifier:
%
matches the character % literallyg 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
版权声明:本文标题:javascript - Regular expression to get all words inside specific patterns (% %) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741550475a2384849.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论