Replace all special characters in the string IN C #

I would like to find all the special characters in the string and replace with Hyphen ( - )

I am using the code below

string content = "foo,bar,(regular expression replace) 123"; string pattern = "[^a-zA-Z]"; //regex pattern string result = System.Text.RegularExpressions.Regex.Replace(content,pattern, "-"); 

Conclusion

Foo bar - regex replacement ----

I get a hyphen multiple occurrence (---) in out put.

I would like to get something like this

Foo-bar-regex replacement

How to achieve this?

Any help would be appreciated

Thanks deep

+2
source share
3 answers

why not just do this:

 public static string ToSlug(this string text) { StringBuilder sb = new StringBuilder(); var lastWasInvalid = false; foreach (char c in text) { if (char.IsLetterOrDigit(c)) { sb.Append(c); lastWasInvalid = false; } else { if (!lastWasInvalid) sb.Append("-"); lastWasInvalid = true; } } return sb.ToString().ToLowerInvariant().Trim(); } 
+11
source

Try the pattern: "[^a-zA-Z]+" - replace one or more non-alpha (can you enable numerical, though?).

+9
source

Does this work?

 string pattern = "[^a-zA-Z]+"; 
+1
source

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


All Articles