简体   繁体   English

如何编写正则表达式以排除字符串中的某些特殊字符?

[英]How to write a regular expression for excluding some special characters from string?

I want to exclude the following characters from my string: 我想从字符串中排除以下字符:

\--
'
<
>

Please tell me how to write a regular expression for this. 请告诉我如何为此编写一个正则表达式。

Personally I'd just use string.Replace. 我个人只是使​​用string.Replace。 Regular expressions are great, but should be used wisely. 正则表达式很棒,但是应该明智地使用。

If your regex dialect supports lookaheads: 如果您的正则表达式方言支持先行:

^(?:(?!\\--|['<>]).)*$

However, in some languages it might be cleaner to have a simple manual check rather than use a regex. 但是,在某些语言中,进行简单的手动检查而不是使用正则表达式可能会更干净。

string s = Regex.Replace(SomeString, "[\-'<>]", "");

希望这可以帮助。

If the question is how to remove \\-- and ' and < and > from a string then this regex does the job: 如果问题是如何从字符串中删除\\--以及'<> ,则此正则表达式可以完成此工作:

['<>]|\\--

or in C# 或在C#中

resultString = Regex.Replace(subjectString, @"['<>]|\\--", "");

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

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