Regex for specific pattern and group issue

Viewed 38

using regex on golang and having hard time to group three names from the following statements:

Hello Planet Earth 2022 - R1 3 Hell John v Tom v Ford

Hello World 2022 - R2 3 Hell - John v Tom v Ford

I'm trying to group "John" "Tom" "Ford" with the following regex:

^(?i).+? . R\d 3 Hell (.+?)[,|v] (.+?)[,|v] (.+?)$

The issue is that it groups "- John" for second statement and I need "John" only.

Any ideas how can it be adjusted?

thanks

2 Answers

Not sure how correct it is, but having tested here, I came up with this...

^(?i).+? . R\d 3 Hell[\s-]* (.+?)[,v] (.+?)[,v] (.+?)$

As you seem to match single spaces, you can optionally match a dash and a space.

Note that the last .+ does not have to be non greedy as it is the last part of the pattern, and the character class [,v] does not need a pipe char if you do not intent to match that as a character.

^(?i).+? . R\d 3 Hell (?:- )?(.+?) [,v] (.+?)[,v] (.+)

Regex demo

Related