简体   繁体   中英

How to extract text using Regular expression (RegEx)?

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 _,@,&,*

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.

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

var matches = str.match(/#(.+?)\$/gi);

jsFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM