Surjeet Singh
Surjeet Singh

Reputation: 11939

Neglect a pattern using Regex

I need help to neglect a pattern while searching substring using regex. For example, in below string

Hello *testing [*_*] message* text or

Hello *testing [_*_*] message* text * additional* message or

Hello testing [*_*_] message* text * additional* message* or

Hello testing [_*_*_] message* text * additional* message*

I need to find out all * to replace with html bold tag, except those which comes within square brackets '[]'. But when I run this regex [*]((?s).*?)[*], It also include * within [], and replace those as well. How can I ignore [* and *] combination while this search.

Any help will be appreciated.

EDIT:

Basically I wanted to ignore matching for given character (eg *) if it is within square brackets [ and ].

Upvotes: 1

Views: 657

Answers (3)

The fourth bird
The fourth bird

Reputation: 163362

You could match what you don't want and keep the asterix in a capturing group using an alternation.

The in the replacement, wrap the value of the first capturing group in a html bold tag

\[[^*\]]*\*[^\]]*\]|(\*)

That will match:

  • \[[^*\]]*\*[^\]]*\] Match [ ... ] with an * in between using a negated character class [^
  • | Or
  • (\*) Capture group 1, match an asterix

Regex demo

Or use the shorter version which will not account for matching an asterix but matches from an opening till a closing square bracket

\[[^\]]+\]|(\*)

Regex demo

Upvotes: 0

schmidt9
schmidt9

Reputation: 4528

What about pattern (\s+\*)|(\*\s+), it matches * plus any number of spaces after or before it.

Edit

(\*\s*\w*\s*\*)|(\*\s*\w*\s*\[\*.*\*\]\s*\w*\s*\*)

You can check it here

Upvotes: 1

can
can

Reputation: 444

The pattern (?<!\[)\*(?!\])(.*?)(?<!\[)\*(?!\]) -although bit ugly- does what you really want in the comments.

For the string Hello *testing [*_*] message* text * additional* message it returns testing [*_*] message, additional

The (?<!\[)\*(?!\]) part only matches with a valid "*"

Here is how it works.

Upvotes: 1

Related Questions