Reputation: 17064
I have such expression;
collection = collection.Where(x => Regex.IsMatch(x, "[a-zA-Z0-9+#-\\.\\s]+", RegexOptions.IgnoreCase)).ToList();
before filtering, collection have such elements:
a+1, a#1, a-1, a.1, a 1, ab, a'1, a@1, a*1, a&1, a:1, a!1
after, I want only following elements to stay:
a+1, a#1, a-1, a.1, a 1, ab
but no element is thrown away.
I need to preserve only elements which consist of: letters, numbers, plus, hash, minus, dot, whitespaces.
How to correct this regex expression ?
Upvotes: 2
Views: 117
Reputation: 172230
Your regex checks if the element contains a substring matching the text. Since all of your elements contain a
(which matches the regular expression), all elements are preserved.
If you want the substring to match exactly, enclose your regular expression in ^...$
(marking the beginning and the end of the text):
... Regex.IsMatch(x, "^[a-zA-Z0-9+#-\\.\\s]+$", ...
EDIT: In addition, you need to move the dash -
to the end of the group:
... Regex.IsMatch(x, "^[a-zA-Z0-9+#\\.\\s-]+$", ...
Otherwise, #-\\.
matches all characters from #
to .
.
Upvotes: 3