从字符串读取到字符串结尾

时间:2017-05-30 08:47:21

标签: c# regex

嗨我有一个简单的问题,但我不是正则表达式:我有一个看起来像这样的字符串:

main

使用正则表达式我试图从错误代码中获取文本:但没有它,到字符串的末尾

到目前为止,我已经:

Some text

Error codes:

10001 iTPM full self test
10003 less than minimum required
10004 bad tag value
10005 bad param size 
10006 fail check

它有效,但它是一个延伸的解决方案,我想用读取结束替换最后一组,但到目前为止没有运气。

文本包含断路器,因为需要此信息。

让我们说c#将是我选择的语言

预期结果如下:

(?<=Error codes:\n)(?s)(.*?)(fail check)

我想读到字符串的结尾,因为我无法确定是否会添加一些新代码。

2 个答案:

答案 0 :(得分:1)

尝试使用以下正则表达式,从两个换行符的错误代码中查看。

(?<=Error codes:\n\n)[\w\s]+

RegexDemo

答案 1 :(得分:1)

如果“让我们说 c#将是我选择的语言”我建议合并 Linq 正则表达式

using System.Linq;
using System.Text.RegularExpressions;

...

string source =
  @"Some text

Error codes:

10001 iTPM full self test
10003 less than minimum required
10004 bad tag value
10005 bad param size
10006 fail check";

var result = source
  .Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
  .SkipWhile(line => !line.StartsWith("Error codes:"))
  .Select(line => Regex.Match(line, @"^(?<code>[0-9]+)\s*(?<name>.+)$"))
  .Where(match => match.Success) // Or .TakeWhile(match => match.Success)
  .Select(match => $"{match.Groups["code"].Value} {match.Groups["name"].Value}")
  .ToArray(); // let's represent result as an array

测试:

Console.Write(string.Join(Environment.NewLine, result));

结果:

10001 iTPM full self test
10003 less than minimum required
10004 bad tag value
10005 bad param size
10006 fail check