How to match all inside asteriks without spaces between them

Viewed 62

I want to match all strings between 2 asterisks without spaces at the start or at the end, also I don't want to match only asterisks text.

For example:

* text* //don't match
******** //don't match
*text * //don't match
* text * //don't match
*  text* //don't match
*text* //match
*Hello World !* //match

I have tried:

(?<=\*)(?!\s)(.*?)(?!\s)(?=\*)

But it's only working on the space in the start, as you can see: https://regex101.com/r/Hpe0br/3/

1 Answers

Instead of negative lookarounds, try using negated character sets instead: [^\s*] will match any character which isn't a space character or an asterisk. Add it to the beginning and end, just between the lookbehind and lookahead. Also, you probably don't want (.*?), because the . will also undesirably match *s:

(?<=\*)[^\s*](?:[^*]+[^\s*])?(?=\*)

https://regex101.com/r/Hpe0br/6

The inner group (?:[^*]+[^\s*])? is optional to allow for single-character matches, like *a*.

Also note that if you're using Javascript, lookbehind is a pretty new feature - no older browser supports it, and it's not transpilable. You might consider matching the *s and capturing the text between the *s in group instead:

\*([^\s*](?:[^*]+[^\s*])?)\*

The substring you want will be in the first captured group.

https://regex101.com/r/Hpe0br/7

Related