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 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!

link|improve this question

70% accept rate
feedback

2 Answers

up vote 1 down vote accepted
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?]']
link|improve this answer
Thank you Ben. Using those characters probably wasn't the best. Your function works great. I really appreciate your help :) – DrZ Oct 10 '11 at 23:48
feedback

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

link|improve this answer
Note that instead of [^\?]* you can just do .*?: The latter means "match the shortest possible match", which in this case will be everything up until the first "?]" it finds, but nothing more. – Ben Lee Oct 10 '11 at 23:52
I knows this is lazy alg, but my expression works too ))) – verybadbug Oct 10 '11 at 23:59
Thanks verybadbug. In using Ben's str above, I tried this: var p = str.match([\?([^\?]*)\?]); but can't get it to work because of the syntax. Am I missing something obvious? thank you. – DrZ Oct 11 '11 at 0:07
missing backslash for first and last brackets – verybadbug Nov 2 '11 at 12:13
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.