-3

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

2 Answers2

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
0

Try this:

^.*(?=.*[@#$%^&+=(){}<>!~_*?]).*$
Chintan
  • 133
  • 8