regexgoregex-lookaroundsregex-groupregex-negation

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


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

Solution

  • Solved with the following regex pattern

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