简体   繁体   中英

Match everything between certain characters

Wow, I suck at regex

http://regex101.com/r/lM8oX3

([*][.]+[*])

I'm trying to match text such as this:

*hello*

Just try with following regex:

(\*[^*]+\*)

In your regex you have [.] which in fact searches for dots because in [] it loses its special context and is treated as a normal character. You should better use .+ then but it will match also * characters. So use my above solution then.

Live demo

This will capture

var text = "asdfasdf *hello*";
console.log( text.match(/([*][^*]+[*])/)[1]);

But that only grabs the first match;

If you want all matches

var text = "asdfasdf *hello* asdffdsa  *asdf*";
var matches = text.match(/([*][^*]+[*])/g);

if(matches.length > 1) {
   for(var i=1; i<matches.length; i++) {
       console.log(matches[i]);
   }
}

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