Regex to match asterisk only if some text is present in between

Viewed 412

I have a regex pattern that detects the whole pattern, that is, asterisks along with the text in between.

Pattern: (\*|__)(.*?)\1

I want it to only match the asterisks, when the words are present in between. Example:

*This is one* This is some other text *New word* Another text another* and there is some more text
  • Asterisks of This is one should be detected;
  • Asterisks of New word should be detected;
  • Last asterisk shouldn't be detected, as it doesn't have any closing one.

I tried several ways, but couldn't find a way, in which the middle words are not detected and only the asterisk.

Programming Language: Typescript (Angular)

Example 2:

*Project Name:* This is some other text *New word* Another text another and there is some more text
1 Answers

You can use

/(\*|__)(?!\s)(.+?)(?<!\s)\1/g

See the regex demo. Since you want to actually enclose * with tags, you may use the <i>$2</i> replacement pattern where $2 is a backreference to the Group 2 value.

Details:

  • (\*|__) - Group 1: * or __
  • (?!\s) - no whitespace is allowed immediately to the right of the current location
  • (.+?) - Group 2: any one or more chars other than line break chars as few as possible
  • (?<!\s) - no whitespace is allowed immediately on the left of the current location
  • \1 - the same value as in Group 1 (* or __).

See the JavaScript demo:

let text = '*This is one* This is some other text *New word* Another text another* and there is some more text **';
text = text.replace(/(\*|__)(?!\s)(.+?)(?<!\s)\1/g, '<i>$2</i>');
console.log(text);

Related