gpt4 book ai didi

c# - 提取字符串的结尾

转载 作者:行者123 更新时间:2023-11-30 20:50:13 24 4
gpt4 key购买 nike

我有以下字符串:

 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. .*? 尝试使用最少的字符。在你的情况下为零。
  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());

关于c# - 提取字符串的结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22734216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com