Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim Non-alphanum from beginning and end of string

Tags:

c#

.net

regex

what is the best way to trim ALL non alpha numeric characters from the beginning and end of a string ? I tried to add characters that I do no need manually but it doesn't work well and use the . I just need to trim anything not alphanumeric.

I tried using this function:

   string something = "()&*1@^#47*^#21%Littering aaaannnndóú(*&^1#*32%#**)7(#9&^";
   string somethingNew = Regex.Replace(something, @"[^\p{L}-\s]+", "");

But it removes all characters that are non alpha numeric from the string. What I basically want is like this:

"test1" -> test1
#!@!2test# -> 2test
(test3) -> test3
@@test4---- -> test4

I do want to support unicode characters but not symbols..

EDIT: The output of the example should be:

Littering aaaannnndóú

Regards

like image 784
circler Avatar asked Sep 18 '25 01:09

circler


1 Answers

Assuming you want to trim non-alphanumeric characters from the start and end of your string:

s = new string(s.SkipWhile(c => !char.IsLetterOrDigit(c))
                .TakeWhile(char.IsLetterOrDigit)
                .ToArray());
like image 60
Douglas Avatar answered Sep 20 '25 14:09

Douglas