How to regex - pattern with literal asterisk

Viewed 181

I have 2 variants of strings:

  1. some_prefix.needed part*some_suffix
  2. some_prefix.needed part

I need only 'needed part' to be matched.

Left boundary is always dot.

Right boundary is asterisk (if exists) or end of line.

Already tried:

/.*[.](.*)[*].*/ - is working for first case

/.*[.](.*)/ - is working for second case

How to do the same with one regex?

2 Answers

You can use

/\.([^*]+)/

See the regex demo.

Details

  • \. - a dot
  • ([^*]+) - Group 1: any one or more chars other than a *.

You can also make sure you get the rightmost match by using .* before the pattern (as in the original regex):

/.*\.([^*]+)/

If supported, you might also use a lookbehind to assert a . to the left.

(?<=\.)[^*]+

The pattern matches:

  • (?<=\.) Positive lookbehind, assert . directly to the left
  • [^*]+ Match 1+ times any char except * using a negated character class

Regex demo

Related