Find NOT matching characters in the regex string?

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

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

this is normal. But what would I like to print every invalid character on this line? As in the example SOMEString => invalid characters: t, r, i, n, g. Any ideas?

+4
source share
3 answers

Use LINQ. Below is an array of 5 elements that do not match the regular expression.

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

The output will be:

 t r i n g 

EDIT:

It looks like you want to treat all lowercase characters as an invalid string. You can try:

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

In your example, the regular expression will succeed for a single character, since it searches for the last character, if it is not uppercase, and your string has such a character.

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

(updated after comments by @Chris)

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

eg:.

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

Or if you want a single line:

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

Try the following:

 char[] list = new char[5]; Regex r = new Regex("[^AZ]*$"); 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

0
source

Source: https://habr.com/ru/post/1433734/


All Articles