How con match optinal groups if exits?

Viewed 68

I have the following examples strings:

(1-0) PK-35 - Women

(2-2) PK-35 Women

(1-0) Real Betis - Women

(2-2) Real Betis Women

There are ladies football teams and i want capture the name without the genres. Name and genre can be separate or no by a "-".

The capture solution i want are in strong. The problem is with PK-35 because of it have a "-" in the name. My expression is

([\w+\s-]*) ( - )?Women

but in the first expression is matching PK-35 -, because "-" is allow in the first group. How can do it to capture the name without the "-" separation if exist?

2 Answers

You can make the match specific matching the - between word characters instead of repeating the character class with hyphen and whitespace char to overmatch it.

Then match a space and make the following - and space optional.

The value is in capture group 1.

\b(\w+(?:[ -]\w+)*) (?:- )?Women\b

Explanation

  • \b A word boundary
  • ( Capture group 1
    • \w+ Match 1+ word chars
    • (?:[ -]\w+)* Optionally repeat either a space or - and 1+ word chars
  • ) Close group 1
  • (?:- )? Match a space with an optional - and space
  • Women\b Match Women and a word boundary

Regex demo

You can use

(\w[\w\s-]*?)\s+(?:-\s+)?Women

See the regex demo. Details:

  • (\w[\w\s-]*?) - Group 1: a word char followed with zero or more word, whitespace or - chars as few as possible
  • \s+ - one or more whitespaces
  • (?:-\s+)? - an optional non-capturing group matching one or zero occurrences of a hyphen and then one or more whitespaces
  • Women - a literal string.
Related