提取字符串的结尾

时间:2014-03-29 17:16:47

标签: c# regex

我有以下字符串:

 Hey this is a test

我正在尝试使用以下正则表达式提取它:

 string buffer = "Hey this is a test";
 Regex r = new Regex("Hey this is a (.*?)", RegexOptions.Multiline);
 Match m = r.Match(buffer);

但由于某种原因,我无法提取它。有什么建议?谢谢!

1 个答案:

答案 0 :(得分:4)

  1. .*?尝试使用最少量的字符。在你的情况下为零。
  2. ()是一个群组。结果是m.Groups[1]

    string buffer = "Hey this is a test";
    Regex r = new Regex("Hey this is a (.*)", RegexOptions.Multiline);
    Match m = r.Match(buffer);
    Console.WriteLine(m.Groups[1]); // test
    
  3. 最好使用更简单的代码。例如,要从字符串中取出最后一个单词,您可以将字符串拆分为' '并取最后一个元素:

    string buffer = "Hey this is a test";
    Console.WriteLine(buffer.Split(' ').Last());
    
相关问题