Check string for invalid characters? Smartest way?

I would like to check some string for invalid characters. With invalid characters I mean characters that should not be there. What characters are these? This is different, but I think thats not that importan, important is how should I do that and what is the easiest and best way (performance) to do that?

Let say I just want strings that contains 'A-Z', 'empty', '.', '$', '0-9'

So if i have a string like "HELLO STaCKOVERFLOW" => invalid, because of the 'a'. Ok now how to do that? I could make a List<char> and put every char in it that is not allowed and check the string with this list. Maybe not a good idea, because there a lot of chars then. But I could make a list that contains all of the allowed chars right? And then? For every char in the string I have to compare the List<char>? Any smart code for this? And another question: if I would add A-Z to the List<char> I have to add 25 chars manually, but these chars are as I know 65-90 in the ASCII Table, can I add them easier? Any suggestions? Thank you


You can use a regular expression for this:

Regex r = new Regex("[^A-Z0-9.$ ]$");
if (r.IsMatch(SomeString)) {
    // validation failed

To create a list of characters from A-Z or 0-9 you would use a simple loop:

for (char c = 'A'; c <= 'Z'; c++) {
    // c or c.ToString() depending on what you need

But you don't need that with the Regex - pretty much every regex engine understands the range syntax (A-Z).

Need Your Help

Set text table hsqldb java exception

java database file exception hsqldb

I have a matrix save in a txt file and I want to load it into an hsqldb table where each column in the matrix is loaded into a column in the table.

WPF/C# Combobox DataBinding

c# .net wpf xaml binding

To begin I would like to apologize for my english which is far from perfect (its not my native language...).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.