简体   繁体   English

正则表达式,仅在当前字符串中存在时匹配

[英]Regex, match only if it exists in the current string

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] [评论]喵[/127.0.0.1]
  • [COMMENT] Shadow[/127.0.0.1] [评论]阴影[/127.0.0.1]
  • [COMMENT] [email] Foxy[/127.0.0.1] [评论] [电子邮件]狡猾[/127.0.0.1]
  • [COMMENT] [email2] PerfectAim[/127.0.0.1] [评论] [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 >:). (在正则表达式中是可选的,因此,如果它不在字符串中,则不执行任何操作,只是跳过电子邮件部分,对不起我的英语>:抱歉)。

Using groups... 正在使用群组...

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

var match = regexUserCommented.Match(test);

if (match.Groups.Count == 5)
{
    Console.WriteLine("==> {0}", match.Groups[4].Value);
}
else
{
    Console.WriteLine("==> Not matched");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM