The string I want to check must have a special character. I've been looking for it here in the forum, but I found only this thread and this does not really help me
Asked
Active
Viewed 350 times
-3
-
1If that thread is no help then I think you need to explain a bit (quite a lot) more about what you are trying to do. With what you've tried already. – spodger Apr 19 '18 at 12:04
-
1welcome to SO ... please refer to https://stackoverflow.com/help/how-to-ask for help about asking your question in a way suitable for SO – DarkSquirrel42 Apr 19 '18 at 12:07
-
`[#?!@$%^&*-]` or something like this – Dmitry Bychenko Apr 19 '18 at 12:08
2 Answers
1
When you
want to check must have a special character
You have to decide what the special character is (e.g. are '{'
, TAB
, .
are special ones?). There are several options. Let's declare (positive)
#?!@$%^&*-
to be the only special characters. In this case we can check
string special = "#?!@$%^&*-";
bool hasSpecial = Regex.IsMatch(source, $"[{Regex.Escape(special)}]+");
Or (Linq)
bool hasSpecial = source.Any(c => special.Contains(c));
On the contrary, we can say (negative declaration) that the special character is anyone which is not alphanumeric.
bool hasSpecial = Regex.IsMatch(source, @"\W+");
Or (Linq)
bool hasSpecial = source.Any(c => !char.IsLetterOrDigit(c));

Dmitry Bychenko
- 180,369
- 20
- 160
- 215