Check for special characters (/*-+_@&$#%) in a string?
C#RegexC# Problem Overview
How do I check a string to make sure it contains numbers, letters, or space only?
C# Solutions
Solution 1 - C#
Simple:
function HasSpecialChars(string yourString)
{
return yourString.Any( ch => ! Char.IsLetterOrDigit( ch ) )
}
Solution 2 - C#
The easiest way it to use a regular expression:
https://stackoverflow.com/questions/336210/regular-expression-for-alphanumeric-and-underscores
Using regular expressions in .net:
http://www.regular-expressions.info/dotnet.html
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if(regexItem.IsMatch(YOUR_STRING)){..}
Solution 3 - C#
string s = @"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
Solution 4 - C#
Try this way.
public static bool hasSpecialChar(string input)
{
string specialChar = @"\|!#$%&/()=?»«@£§€{}.-;'<>_,";
foreach (var item in specialChar)
{
if (input.Contains(item)) return true;
}
return false;
}
Solution 5 - C#
String test_string = "tesintg#$234524@#";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
// Good-to-go
}
An example can be found here: http://ideone.com/B1HxA
Solution 6 - C#
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
Solution 7 - C#
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
Solution 8 - C#
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
Solution 9 - C#
A great way using C# and Linq here:
public static bool HasSpecialCharacter(this string s)
{
foreach (var c in s)
{
if(!char.IsLetterOrDigit(c))
{
return true;
}
}
return false;
}
And access it like this:
myString.HasSpecialCharacter();
Solution 10 - C#
private bool isMatch(string strValue,string specialChars)
{
return specialChars.Where(x => strValue.Contains(x)).Any();
}
Solution 11 - C#
Create a method and call it hasSpecialChar with one parameter and use foreach to check every single character in the textbox, add as many characters as you want in the array, in my case i just used ) and ( to prevent sql injection .
public void hasSpecialChar(string input)
{
char[] specialChar = {'(',')'};
foreach (char item in specialChar)
{
if (input.Contains(item)) MessageBox.Show("it contains");
}
}
in your button click evenement or you click btn double time like that :
private void button1_Click(object sender, EventArgs e)
{
hasSpecialChar(textbox1.Text);
}
Solution 12 - C#
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
- Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
- Add "
using Extensions;
" to the top of your code. "smith23@".IsAlphaNumeric()
will return False whereas"smith23".IsAlphaNumeric()
will return True. By default the.IsAlphaNumeric()
method ignores spaces, but it can also be overridden such that"smith 23".IsAlphaNumeric(false)
will return False since the space is not considered part of the alphabet.- Every other check in the rest of the code is simply
MyString.IsAlphaNumeric()
.