Regex OR results in two separate groups, how do I make capture it as a single group?

61 views Asked by At

I'm trying to capture the username for the following input string in GoLang regex, I expected anonymous and prettygurl91 to be in a single group, but it wasn't the case for the following pattern.

Input:

[Twitter] An anonymous user has posted a photo on 03-24-2024!
[Twitter] User prettygurl91 has posted a video on 03-25-2024!

Pattern:

^\[Twitter\] (?:User (.*?)|An (anonymous) user) has posted a (.*) on (.*)\!

Resulting groups:

Resulting group for [Twitter] An anonymous user has posted a photo on 03-24-2024!

  1. Nil
  2. anonymous
  3. photo
  4. 03-24-2024

Resulting group for [Twitter] User prettygurl91 has posted a video on 03-25-2024!

  1. prettygurl91
  2. Nil
  3. video
  4. 03-25-2024

What is was expecting was the following input strings to be grouped like so

  1. prettygurl91 / anonymous
  2. photo / video
  3. 03-24-2024 / 03-25-2024
2

There are 2 answers

0
Vince Jerald Villamora On BEST ANSWER

Solved with the following regex pattern

^\[Twitter\] (?:User|An) (.\S*).* has posted a (.*) on (.*)\!
6
Tim Biegeleisen On

You have multiple capture groups enabled which don't seem to serve any purpose. And the one capture group you want to use has been turned off. Try this version:

^\[Twitter\] (User \w+|An Anonymous user) has posted a .* on .*!