LINQ query for string.replace

In search of help where any string is specified, return a string with only alphanumeric characters and replace all non-alphanumeric characters with _

so the string "ASD @ # $ 123" becomes "ASD ___ 123"

etc.

thanks

+4
source share
3 answers

For most string operations, you would be better off (in terms of both efficiency and ) if you use regular expressions rather than LINQ:

string input = " ASD@ #$123"; string result = Regex.Replace(input, "[^A-Z0-9]", "_", RegexOptions.IgnoreCase); 

If you want to store the Unicode alphanumeric character, including non-ASCII characters, such as é , we can use the non-word character to make it even easier:

 string input = " ASD@ #$123"; string result = Regex.Replace(input, @"\W", "_"); 

For comparison, this is the same conversion performed using LINQ (allowing ASCII letters and numbers):

 string input = " ASD@ #$123"; string result = new string(input.Select(c => c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' ? c : '_' ).ToArray()); 

Or, if Char.IsLetterOrDigit meets your requirements:

 string input = " ASD@ #$123"; string result = new string(input.Select(c => char.IsLetterOrDigit(c) ? c : '_').ToArray()); 

Note that Char.IsLetterOrDigit will contain non-ASCII letters and is comparable to the \w character class of words, the negation of which was used in our second example.

Change As Steve Wortham noted, LINQ versions are actually more than 3 times faster than a regular expression (even if a Regex instance is created in advance using RegexOptions.Compiled used).

+10
source
 char[] unwanted = new[] {'@', '#', '$'}; foreach(var x in query) { x.SomePropertyName = string.Join("_", x.SomePropertyName.Split(unwanted)); }; 

LINQ lambda expression to replace multiple characters in a string

0
source

Here is the function:

  String ReplaceWrongChars(String baseString) { Regex rx = new Regex("[^A-Za-z0-9 ]", RegexOptions.CultureInvariant); String rv = rx.Replace(baseString, "_"); return rv; } 

If you don't need spaces, use "[^ A-Za-z0-9]" as a regular expression.

0
source

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


All Articles