I am implementing a regex pattern to a list of strings. Example of such a string is: "MNT-PUT-Y0-HAS90"
. There are other UNWANTED strings as well, like: "MNT-PUT-HAS90"
.
When I execute the below code, I get "" for the unwanted one, which I guess how Regex works. And, I get "MNT-PUT-Y0-HAS90"
for the wanted one.
The question is: How can I completely ignore the occurrence of MNT-PUT-HAS90. I want to retrieve results for string - "MNT-PUT-Y0-HAS90"
only.
I have implemented the below code for this:
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
I tried changing the code to the below, but it shows me an error: "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
EDIT: Just tried this:
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
I get no error but do not get the desired output either.
You need to use
Regex.IsMatch(x, "^[A-Z]+-[A-Z]+-[A-Z]+[0-9]+-[A-Z]+[0-9]+$")
See how this regex works .
Details
^
- start of the string [AZ]+
- 1+ ASCII uppercase letters -
- a hypehn [AZ]+-
- - 1+ ASCII uppercase letters and a hyphen [AZ]+[0-9]+-
- 1+ ASCII uppercase letters, 1+ ASCII digits and then a hyphen [AZ]+[0-9]+
- 1+ ASCII uppercase letters, 1+ ASCII digits $
- end of string. Code:
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;
If the match is expected anywhere inside a longer string, remove ^
and $
anchors.
It was a very easy solution to it but somehow I was missing it... I did the below to resolve the issue:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.