wyc
wyc

Reputation: 55293

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 * * *?

Upvotes: 0

Views: 82

Answers (3)

Peter Seliger
Peter Seliger

Reputation: 13431

A capturing regex like ... /[*\s+]*\*([^*]+)\*/g ... executed by matchAll and an additional mapping 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)
);

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163457

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

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

Regex demo

Upvotes: 3

AaronJ
AaronJ

Reputation: 1170

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

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

https://regexr.com/63ofo

Upvotes: 1

Related Questions