sasharz
sasharz

Reputation: 789

Regex replace special characters except leading and trailiing

I want to use regex to remove special characters from a string but only if the characters are located in the middle of the string. Leading and trailing should stay. Example:

a+b+c will become abc;

a+bc+ will alos become abc, because the trailing + should stay.

I have a regex that will replace all special characters

var newString = Regex.Replace(myString, @"[^\w]", string.Empty)

I don't know how to skip first and last characters. Considering that the string length could start from, without regex I'd have to always check length if I want to substring, etc. It's all doable, but it would be nice if it's done with regex with one line of code. Is it possible?

Upvotes: 1

Views: 461

Answers (1)

juharr
juharr

Reputation: 32266

You can use negative look ahead and look behind with the anchors

(?<!^)[^\w](?!$)

That will match non-word characters that are not the very first or very last, meaning it would match the second plus in "++abc" and thus turn that into "+abc".

Upvotes: 5

Related Questions