【问题标题】:Regex to get a string after a character [duplicate]正则表达式在字符后获取字符串[重复]
【发布时间】:2014-05-04 23:12:22
【问题描述】:

我有 A1234-111,D890-222,A456-333 等字符串... 如何使用正则表达式获取 - 字符之后的所有内容; 右手边

【问题讨论】:

  • 你当前的代码哪里出错了?
  • 提示:对于手头的示例,您可能会使用子字符串函数。
  • 至少有 5 种方法可以做到这一点......
  • @Kent 5 可能趋于无穷大。

标签: c# .net regex


【解决方案1】:

正则表达式的亮点在于能够命名和提取匹配项(用正则表达式命名匹配捕获组)。

在这里,我已经命名了模式中的两侧,一旦获得,只需从需要的一侧中提取。

var data = "A1234-111";
var pattern = @"(?<Pre>[^-]+)-(?<Post>.+)";

var mtch = Regex.Match(data, pattern);

Console.WriteLine ("Pre is {0} and Post is {1}", mtch.Groups["Pre"], mtch.Groups["Post"]);

// Result
// Pre is A1234 and Post is 111

【讨论】:

    【解决方案2】:

    你可以使用正则表达式

    (?<=-)\d+
    

    (?&lt;=...) 是一个后视。

    【讨论】:

      【解决方案3】:

      - 之前的任何内容替换为空字符串。

      string input = " A1234-111";
      input = Regex.Replace(input, @".*?-", "");
      

      【讨论】:

        【解决方案4】:

        拆分两次可能更容易:

        foreach (string s in myString.Split(','))
        {
            string afterHyphen = s.Split('-')[1];
        }
        

        【讨论】:

          【解决方案5】:

          你真的不需要正则表达式,是吗?

          List<string> result = input.Split(',')
              .Select(s => s.Split('-').Last())
              .ToList();
          

          【讨论】:

            【解决方案6】:

            使用 C#,您必须包含 System.Text.RegularExpressions 库,然后运行匹配:

            using System.Text.RegularExpressions;
            ...
              Regex rx = new Regex(@"[^\-]\-(.*)");
              string s = "A1234-111";
              Match m = rx.Match(s);
              System.Diagnostics.Debug.WriteLine("Match is " + m.Groups[1].Value);
            ...
            

            我知道您询问过正则表达式,但您可以对文本进行拆分,只要模式相同:

            string[] parts = s.Split(new char[] { '-' });
            System.Diagnostics.Debug.WriteLine("Split Match is " + parts[1]);
            

            以最有效的方式。 :)

            【讨论】:

              【解决方案7】:

              如果您需要搜索整个字符串,请使用:

              (?[A-Za-z]\d+\-(\d+),)+
              

              第一组不捕获以将逗号之间的项目分组,第二组正在捕获以实际匹配您的数字。

              如果需要单独搜索逗号分隔的字符串,最好使用String.Split,或者:

              [A-Za-z]\d+\-(\d+)
              

              您可以将[A-Za-z]\d 替换为\w

              【讨论】:

                猜你喜欢
                • 2018-07-28
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2015-10-30
                • 1970-01-01
                • 2013-03-12
                • 1970-01-01
                • 2013-10-12
                相关资源
                最近更新 更多