简体   繁体   English

正则表达式替换特殊字符,但前导和尾随除外

[英]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 + b + c将变为abc;

a+bc+ will alos become abc, because the trailing + should stay. a + bc +将失去abc,因为结尾的+应该保留。

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? 可能吗?

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". 这将匹配不是第一个也不是最后一个的非单词字符,这意味着它将匹配“ ++ abc”中的第二个加号,从而将其转换为“ + abc”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM