tollmanz
tollmanz

Reputation: 3223

Regex match everything except a specific character

I am trying to set up a regex that will match the following:

*test*
*t*
*te*

But, I do not want it to match:

*test**

The general rules are:

I have generated the following regex:

(\s|^)\*([^\*].+?[^\*])\*(\s|$)

This nearly satisfies my requirements; however, because of the two [^\*] groups within the second capturing group, it seems to require that capturing group to be 3 characters or more. *tes* matches, but *t* and *te* do not.

I have three specific questions:

  1. Why does the character negation lead to the 3 character limit?
  2. Is there a better way to express "any character except" than I have done here?
  3. Any thoughts on a better regex to satisfy my requirements?

Upvotes: 2

Views: 5446

Answers (1)

Tushar
Tushar

Reputation: 87233

The problem in the regex is an extra . in the capturing group

[^\*].+?[^\*]
     ^

This will match a character except * followed by one or more of any characters except newline.

As the character class is repeated twice, you can use + quantifier to match one or more characters.

(\s|^)\*([^\*]+?)\*(\s|$)

Demo


You can also use non-capturing groups to exclude the extra matches.

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

Demo 2

Upvotes: 7

Related Questions