【问题标题】:How can I cut out the below pattern from a string using Regex?如何使用正则表达式从字符串中删除以下模式?
【发布时间】:2015-07-25 14:59:04
【问题描述】:

我有一个字符串,其中包含单词“TAG”,后跟一个整数、下划线和另一个单词。

例如:“TAG123_Sample”

我需要剪切“TAGXXX_”模式,只得到单词 Sample。这意味着我将不得不删除单词“TAG”以及后面的整数和下划线。

我编写了以下代码,但它不起作用。我做错了什么?我怎样才能做到这一点?请指教。

static void Main(string[] args)
    {
        String sentence = "TAG123_Sample";
        String pattern=@"TAG[^\d]_";
        String replacement = "";
        Regex r = new Regex(pattern);
        String res = r.Replace(sentence,replacement);
        Console.WriteLine(res);
        Console.ReadLine();
    }

【问题讨论】:

  • 试试这个:@"TAG\d+_" 因为[^\d] 可能只是说“没有数字将跟随 TAG”所以只需使用 \d+ 表示“超过一位”

标签: c# .net regex visual-studio-2010


【解决方案1】:

您当前正在否定(匹配NOT一个数字),您需要修改正则表达式如下:

String s = "TAG123_Sample";
String r = Regex.Replace(s, @"TAG\d+_", "");
Console.WriteLine(r); //=> "Sample"

解释

TAG      match 'TAG'
 \d+     digits (0-9) (1 or more times)
 _       '_'

【讨论】:

    【解决方案2】:

    您可以为此使用String.Split

    string[] s = "TAG123_Sample".Split('_');
    Console.WriteLine(s[1]);
    

    https://msdn.microsoft.com/en-us/library/b873y76a.aspx

    【讨论】:

      【解决方案3】:

      试试这个肯定会在这种情况下工作:

      resultString = Regex.Replace(sentence , 
          @"^   # Match start of string
          [^_]* # Match 0 or more characters except underscore
          _     # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);
      

      【讨论】:

        【解决方案4】:

        如果您的字符串包含 1 个下划线并且您需要在其后获取子字符串,则不需要正则表达式。

        这是一个基于Substring+IndexOf的方法:

        var res = sentence.Substring(sentence.IndexOf('_') + 1); // => Sample
        

        IDEONE demo

        【讨论】:

          猜你喜欢
          • 2013-11-03
          • 1970-01-01
          • 2011-03-22
          • 1970-01-01
          • 2013-05-23
          • 1970-01-01
          • 2021-01-17
          • 2014-06-20
          • 1970-01-01
          相关资源
          最近更新 更多