Home:ALL Converter>Regex, match only if it exists in the current string

Regex, match only if it exists in the current string

Ask Time:2013-10-04T07:45:27         Author:Yuki Kutsuya

Json Formatter

First of all, sorry for any spelling/grammar errors that may occur. I'm trying to get some complicated regex problem solved but I can't seem to figure out how to. I'm trying to filter out some parts of certain strings. This works, however! There is one line which is optional and that's the second one, the email. How can I tell the regex that this part is optional and should only search for if it exists in the string or not.

Strings

  • [COMMENT] Meow[/127.0.0.1]
  • [COMMENT] Shadow[/127.0.0.1]
  • [COMMENT] [email] Foxy[/127.0.0.1]
  • [COMMENT] [email2] PerfectAim[/127.0.0.1]

What I've tried

Regex regexUserCommented = new Regex(
    @"(\[COMMENT\])\ " +  // COMMENT
    @"(\[.*\]) " +        // Email, this needs to be optional but how?!
    @"(\w(?<!\d)[\w'-]*)" // User
);

if (regexUserCommented.IsMatch(test))
{
    var infoMatches = regexUserCommented.Split(test);
    Console.WriteLine(infoMatches[3]); // User
}

Anyone has any idea how I can make the email section optional? (Optional in the regex, so that if it's not in the string it doesnt do anything, that it just skips the email part, sorry for my bad English >:).

Author:Yuki Kutsuya,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/19170928/regex-match-only-if-it-exists-in-the-current-string
yy