首页 > 解决方案 > 具有遵循特定模式的尾部的字符串的头部

问题描述

我收到的字符串可以等于any + " " + str + "Y"whereany可以是任何字符串,并且字符串可以str等于"1""2""3""5"或。我的目标是提取字符串。"7""10"any

我想出了以下代码:

string pattern = ".* {1Y|2Y|3Y|5Y|7Y|10Y}";
string indexIDTorParse = group.ElementAt(0).IndexID;
Match result = Regex.Match(indexIDTorParse, pattern);
string IndexIDTermBit = result.Value;
string IndexID = indexIDTorParse.Replace($" {IndexIDTermBit}", "");

但它没有赋予权利any

标签: c#regex

解决方案


您应该使用括号来定义一组模式,而不是大括号,并且您可以捕获any部分并直接通过Match.Groups而不是额外替换输入字符串来访问它:

string pattern = @"(.*) (?:[1-357]|10)Y";
string indexIDTorParse = group.ElementAt(0).IndexID;
Match result = Regex.Match(indexIDTorParse, pattern);
string IndexID = "";
if (result.Success) 
{
    IndexID = result.Groups[1].Value;
}

正则表达式匹配:

  • (.*)- 第 1 组:任何 0 个或更多字符,尽可能多(注意,如果您需要将子字符串直到第一次出现nY, use (.*?),它将在后续模式之前匹配尽可能少的字符)
  • - 空间
  • (?:[1-357]|10)- 1, 2,3 ,5 ,7 or10`
  • Y- 一个Y字符。

请参阅正则表达式演示


推荐阅读