开发者

Using regex to extract strings given a pattern in JavaScript

I'm trying to figure out how to grab only the values in between known begin and end strings. For example, using this string:

I need [?Count?] [?Widgets?]

I need the the开发者_JS百科 values Count and Widgets returned.

I tried

[?(.*)?]

and ended up with

I need [
Count
] [
Widgets
]

Is there a way, using these begin and end strings, to parse out the values I need? Or should I try and find a way to change them before parsing out the values? I really appreciate any help you can provide.

Thank you!


var str = "I need [?Count?] [?Widgets?]";
$(str.match(/\[\?.*?\?\]/g)).map(function(i) { return this.match(/\[\?(.*)\?\]/)[1] });
// => ['Count'], 'Widgets']

Note that in the regex, you have to escape [, ], and ? as they are special characters. Also use the g flag at the end of the regex to find all matches. I'm also using .*? instead of .* -- that means non-greedy match or "find the shortest possible match", which is what you want here.

Finally, the results are mapped (using jquery map) to remove the '[?' and '?]' from the results.

Or, if you don't want the special characters removed, don't even use the map:

var str = "I need [?Count?] [?Widgets?]";
str.match(/\[\?.*?\?\]/g);
// => ['[?Count?]'], '[?Widgets?]']


In your regular expression try \[\?([^\?]*)\?\]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜