用于捕获介于 = 和 ; 之间的单词的正则表达式

RegEx for capturing a word in between = and ;

我想 select word2 来自以下 :

word2;word3

word2 位于 ; 和行首之间,除非中间有 =。在那种情况下,我想从 = 而不是行的开头 喜欢

中的 word2
word1=word2;word3

我试过使用这个正则表达式

(?<=\=|^).*?(?=;)

select word2 来自

word2;word3

还有来自

的整个word1=word2
word1=word2;word3

您可以使用可选组来检查后跟等号的单词并捕获第一个捕获组中的值:

^(?:\w+=)?(\w+);

说明

  • ^ 字符串开头
  • (?:\w+=)? 可选的非捕获组匹配 1+ 个单词字符后跟 =
  • (\w+) 在第一个捕获组中捕获 1+ 个字符
  • ; 匹配 ;

看到一个regex demo

在 .NET 中,您还可以使用:

(?<=^(?:\w+=)?)\w+(?=;)

Regex demo | C# demo

应该有这么多选项,最后几个可能是正则表达式。

但是,如果我们希望使用表达式来解决这个问题,让我们从一个简单的表达式开始,然后探索其他选项,可能类似于:

(.+=)?(.+?);

(.+=)?(.+?)(?:;.+)

第二个捕获组有我们想要的 word2

Demo 1

Demo 2

示例 1

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(.+=)?(.+?);";
        string input = @"word1=word2;word3
word2;word3";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

示例 2

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(.+=)?(.+?)(?:;.+)";
        string substitution = @"";
        string input = @"word1=word2;word3
word2;word3";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
    }
}

您可以使用 String class 方法来解决问题,而不是使用正则表达式。

string[] words = str.Split(';');
string word2 = words[0].Substring(words[0].IndexOf('=') + 1);

第一行将行从“;”中拆分出来。假设你只有一个 ';'此语句将您的行分成两个字符串。第二行 returns 第一部分 (words[0]) 的子字符串从第一次出现的 '=' (words[0].IndexOf('=')) 字符的下一个字符 (+1) 开始到结束。如果您的行没有任何“=”字符,它只是从头开始,因为 IndexOf returns -1.

相关文档: