【问题标题】:RegEx for capturing a word in between = and ;用于在 = 和 ; 之间捕获单词的正则表达式
【发布时间】:2019-10-13 06:31:30
【问题描述】:

我想从以下选项中选择word2

word2;word3

word2 介于 ; 和行首之间,除非两者之间有 =。在这种情况下,我想从 = 而不是行首开始 喜欢来自

word2
word1=word2;word3

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

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

从中选择word2

word2;word3

还有整个word1=word2来自

word1=word2;word3

【问题讨论】:

    标签: c# regex regex-lookarounds regex-group regex-greedy


    【解决方案1】:

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

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

    说明

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

    查看regex demo

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

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

    Regex demo | C# demo

    【讨论】:

    • 谢谢。有没有办法直接从正则表达式返回第 1 组?
    • @Krinjon 第二个模式只会给你匹配而不是组,尽管组选项具有不使用环视的优点。例如ideone.com/dUzYIS
    【解决方案2】:

    应该有这么多选项,也许正则表达式是最后一个。

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

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

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

    第二个捕获组有我们想要的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 = @"$2";
            string input = @"word1=word2;word3
    word2;word3";
            RegexOptions options = RegexOptions.Multiline;
    
            Regex regex = new Regex(pattern, options);
            string result = regex.Replace(input, substitution);
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用 String 类方法解决问题,而不是使用常规表达式。

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

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

      相关文档:

      【讨论】:

        猜你喜欢
        • 2017-11-18
        • 2020-06-09
        • 1970-01-01
        • 1970-01-01
        • 2018-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多