1

I need some help with regular expressions in JavaScript.

I have the following string.

var str = "SOme TEXT #extract1$ Some more text #extract2$ much more text #extract3$ some junk";

I want to extract all the text between # and $ into an array or object.

Final output would be:

var result = [extract1,extract2,extract3]

extract1, extract2,extract3 can contain any characters like _,@,&,*

3 Answers 3

2

You can use JavaScript Regular expressions' exec method.

var regex = /\#([^\$]+)\$/g,
    match_arr,
    result = [],
    str = "some #extract1$ more #extract2$ text #extract3$ some junk";
while ((match_arr = regex.exec(str)) != null)
{
   result.push(match_arr[1]);
}
console.log(result);

Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec

Sign up to request clarification or add additional context in comments.

Comments

2

Regex for you will be like #(?<extract>[\s\S]*?)\$

Named group 'extract'will contain the values you want.

As Alex mentioned, if javascript doesnt support named group, we can use numbered group. So modified regex will be #([\s\S]*?)\$ and desired values will be in group number 1.

7 Comments

nice touch with the [\s\S]. how does it perform against [^\$] ?
@yoavmatchulsky, certainly [^\$] is faster than [\s\S]
JavaScript doesn't have named capturing groups. Why do you escape #? Also, why the ? after the *?
@Shekhar Also, I understand the ? now. Ungreedy. How did I forget that?
@alex the *? means its a non-greedy * which means it will capture as little as possible. EG a regex of .*b on a string "aaaababa" will capture "aaaabab" but a non greedy .*?b will capture "aaaab". EDIT beat me to it alex. ;)
|
0
var matches = str.match(/#(.+?)\$/gi);

jsFiddle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.