简体   繁体   中英

Find NOT matching characters in a string with regex?

If Im able to check a string if there are invalid characters:

Regex r = new Regex("[^A-Z]$");
string myString = "SOMEString"; 
if (r.IsMatch(myString)) 
{     
  Console.WriteLine("invalid string!");
} 

it is fine. But what I would like to print out every invalid character in this string? Like in the example SOMEString => invalid chars are t,r,i,n,g. Any ideas?

Use LINQ. Following will give you an array of 5 elements, not matching to the regex.

char[] myCharacterArray = myString.Where(c => r.IsMatch(c.ToString())).ToArray();
foreach (char c in myCharacterArray)
{
    Console.WriteLine(c);
}

Output will be:

t
r
i
n
g

EDIT:

It looks like, you want to treat all lower case characters as invalid string. You may try:

   char[] myCharacterArray2 = myString
                                   .Where(c => ((int)c) >= 97 && ((int)c) <= 122)
                                   .ToArray(); 

In your example the regex would succeed on one character since it's looking for the last character if it isn't uppercase, and your string has such a character.

The regex should be changed to Regex r = new Regex("[^AZ]"); .

(updated following @Chris's comments)

However, for your purpose the regex is actually what you want - just use Matches .

eg:

foreach (Match item in r.Matches(myString))
{
   Console.WriteLine(item.ToString() + " is invalid");
}

Or, if you want one line:

foreach (Match item in r.Matches(myString))
{
   str += item.ToString() + ", ";
}
Console.WriteLine(str + " are invalid");

Try with this:

char[] list = new char[5];
Regex r = new Regex("[^A-Z]*$");
string myString = "SOMEString";

foreach (Match match in r.Matches(myString))
{
    list = match.Value.ToCharArray();
    break;
}

string str = "invalid chars are ";
foreach (char ch in list)
{
    str += ch + ", ";
}

Console.Write(str);

OUTPUT: invalid chars are t, r, i, n, g

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM