简体   繁体   中英

How to match anything between * but not match * * *

I'm using the following regex to match anything between * :

/\*([^*]*)\*/g

It should match this:

*text*

*text*

*text text 
text*

The match messes up if there are * * * in a line:

*text*

* * *

*text*

*text text 
text*

https://regexr.com/63of6

What's the simplest way to prevent * * * from messing up the match? In other words, not matching * * * ?

You could match at least a single non whitespace char other than * in between.

\*[^*]*[^\s*][^*]*\*

Regex demo

A capturing regex like... /[*\s+]*\*([^*]+)\*/g ... executed by matchAll and an additional map ping does the job...

 const sampleText = `*foo* * * * *bar* *baz* *biz**buz* *foo bar baz**biz buz*`; // [https://regex101.com/r/maKxyJ/1] const regX = (/[*\s+]*\*([^*]+)\*/g); console.log( [...sampleText.matchAll(regX)].map(([match, capture]) => capture) );

Does [\* ]*([^*]*)\* work for you?

https://regex101.com/r/q7kYIQ/1/

https://regexr.com/63ofo

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