[英]How to make regex pattern lazy, or how to stop matching on first occurrence?
[英]How to completely discard the occurrence of a string not matching the regex pattern?
我正在对字符串列表实现正则表达式模式。 这样的字符串的示例是: "MNT-PUT-Y0-HAS90"
。 还有其他不需要的字符串,例如: "MNT-PUT-HAS90"
。
当我执行以下代码时,对于不需要的代码,我会得到“”,我猜想它是Regex的工作方式。 而且,对于想要的人,我得到"MNT-PUT-Y0-HAS90"
。
问题是:如何完全忽略MNT-PUT-HAS90的出现。 我只想检索字符串- "MNT-PUT-Y0-HAS90"
。
我已经实现了以下代码:
Store = a.Type == "Machines" ?
string.Join(",", a.Info.Disk.Select(b => b.Store).
Select(x => Regex.Match(x, "[A-Z]+-[A-Z]+-T[0-9]-[A-Z]+[0-9]"))) : null
我尝试将代码更改为以下代码,但是它显示了一个错误: "Cannot convert lambda expression to the intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type"
Store = a.Type == "Machines" ?
string.Join(",", a.Info.Disk.Select(b => b.Store).
Where(x => Regex.Match(x, "[A-Z]+-[A-Z]+-T[0-9]-[A-Z]+[0-9]")).ToString()) : null
编辑:刚刚尝试过此:
Store = a.Type == "Machines" ?
string.Join(",", a.Info.Disk.Select(b => b.Store).
Where(x => Regex.IsMatch(x, "[A-Z]+-[A-Z]+-T[0-9]-[A-Z]+[0-9]")).ToList()) : null
我没有错误,但也没有获得所需的输出。
您需要使用
Regex.IsMatch(x, "^[A-Z]+-[A-Z]+-[A-Z]+[0-9]+-[A-Z]+[0-9]+$")
细节
^
-字符串的开头 [AZ]+
-1+ ASCII大写字母 -
催眠 [AZ]+-
1+ ASCII大写字母和一个连字符 [AZ]+[0-9]+-
1+ ASCII大写字母,1 + ASCII数字和连字符 [AZ]+[0-9]+
-1+ ASCII大写字母,1 + ASCII数字 $
-字符串结尾。 码:
Store = a.Type == "Machines" ?
string.Join(",",
a.Info.Disk
.Select(b => b.Store)
.Where(x => Regex.IsMatch(x, "^[A-Z]+-[A-Z]+-[A-Z]+[0-9]+-[A-Z]+[0-9]+$"))
)
: null;
如果期望在更长的字符串中的任何位置进行匹配,请删除^
和$
锚点。
这是一个非常简单的解决方案,但不知何故我不见了……我做了以下工作来解决该问题:
Store = a.Type == "Machines" && a.Power == "on" &&
string.Join(",", a.Info.Disk.Select(b => b.Store).
Where(x => Regex.Match(x, "[A-Z]+-[A-Z]+-T[0-9]-[A-Z]+[0-9]"))) != "" ?
"Do your stuff" : null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.