加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 具有特定图案的尾部的弦头

发布时间:2020-12-16 01:28:46 所属栏目:百科 来源:网络整理
导读:我收到的字符串可以等于任何“”str“Y”,其中any可以是任何字符串,字符串str可以等于“1”,“2”,“3”,“5”,“7”或“10”.我的目标是提取字符串. 我想出了以下代码: string pattern = ".* {1Y|2Y|3Y|5Y|7Y|10Y}";string indexIDTorParse = group.Elemen
我收到的字符串可以等于任何“”str“Y”,其中any可以是任何字符串,字符串str可以等于“1”,“2”,“3”,“5”,“7”或“10”.我的目标是提取字符串.

我想出了以下代码:

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}","");

但它没有给予任何权利.

解决方法

您应该使用 parentheses来定义一组模式,而不是大括号,您可以捕获任何部分并通过 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,使用(.*?),它将匹配少量字符可能在后续模式之前)
> – 一个空间
>(?:[1-357] | 10) – 1,2,3,5,7or10`
> Y – 一个Y字符.

见regex demo.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读