c# - 具有遵循特定模式的尾部的字符串的头部
问题描述
我收到的字符串可以等于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
。
解决方案
您应该使用括号来定义一组模式,而不是大括号,并且您可以捕获该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,
7or
10`Y
- 一个Y
字符。
请参阅正则表达式演示。
推荐阅读
- java - 使用 Mapstruct 的双向实体方法
- python - Python imaplib:获取第一封未读邮件
- python - 使用列表理解的 2 个元素的元组列表
- dart - 收听未来的清单项目
- javascript - 将 css 应用于 javascript 中的一系列元素
- angular - 如何在 Angular 10 中使用数据绑定扩展 iframe src 中的 html 字符串?
- git - git fsck 结合 --lost-found 和 --unreachable
- php - 未捕获的错误:未定义的常量“FILTER_SANITIZE_MAGIC_QUOTES”
- javascript - 使用节点迭代 firestore 数组字段
- python - Paho MQTT - 日志显示消息已发布但未发送任何内容