C#正则表达式可选命名组

C#正则表达式可选命名组,c#,regex,C#,Regex,我有这样的模式: string ISLTokenPattern = @"\d+:(\s+)?(?<local>\d+)[-][>](\s+)?(?<remote>\d+)\s+(?<wwn>..:..:..:..:..:..:..:..)\s+\d+\s(?<name>.+)\s+[s][p]:\s+\w+.\w+\s+\w+[:]\s+\d+.\w+\s+((?<trunk>TRUNK))?\s"; 在RegExStorm.

我有这样的模式:

 string ISLTokenPattern = @"\d+:(\s+)?(?<local>\d+)[-][>](\s+)?(?<remote>\d+)\s+(?<wwn>..:..:..:..:..:..:..:..)\s+\d+\s(?<name>.+)\s+[s][p]:\s+\w+.\w+\s+\w+[:]\s+\d+.\w+\s+((?<trunk>TRUNK))?\s";
在RegExStorm.Net上,模式匹配所有5行输入。通常,如果某些东西在那里起作用,它在C#中起作用。在我的代码中,匹配在第3、4和5行失败。如果我脱下衣服

((?<trunk>TRUNK))?\s

我注意到您当前正则表达式的一个可能问题是结尾:

\s+((?<trunk>TRUNK))?\s

这可以选择匹配
TRUNK
,后跟一个空格。您使用哪一个取决于您的实际数据。

(?TRUNK))?\s
。。。在.NET正则表达式中,它与什么匹配?在RegexStorm.NET中,它与输入中的“TRUNK”匹配。如果输入中没有“TRUNK”一词,匹配将失败。我不理解您的正则表达式模式,但以
(?:TRUNK.*)结尾应该可以。
应该可以工作。不要拘泥于当前正则表达式,只需调整它,直到它在.NET代码中工作。
\s+(?TRUNK))?\s
。。。这里有一个问题:如果
TRUNK
不存在,那么您的正则表达式将坚持在末尾找到两个或更多的空格。但是你的文本只有一个空格。
  string ISLTokenPattern = @"\d+:(\s+)?(?<local>\d+)[-][>](\s+)?(?<remote>\d+)\s+(?<wwn>..:..:..:..:..:..:..:..)\s+\d+\s(?<name>.+)\s+[s][p]:\s+\w+.\w+\s+\w+[:]\s+\d+.\w+\s+((?<trunk>TRUNK))?\s";


 if (RegexExtensions.TryMatch(out tokenMatch, line, ISLTokenPattern)
        {
            string local = tokenMatch.Groups["local"].Value;
            string remote = tokenMatch.Groups["remote"].Value;
            string wwn = tokenMatch.Groups["wwn"].Value.ToUpper();

            string name = "";
          if (tokenMatch.Groups["name"].Success)
           {
              name = tokenMatch.Groups["name"].Value;
            }
 public static class RegexExtensions
{
    public static bool TryMatch(out Match match, string input, string pattern)
    {
        match = Regex.Match(input, pattern);
        return (match.Success);
    }

    public static bool TryMatch(out MatchCollection match, string input, string pattern)
    {
        match = Regex.Matches(input, pattern);
        return (match.Count > 0);
    }
}
\s+((?<trunk>TRUNK))?\s
\s+((?<trunk>TRUNK\s))?