替换/删除与正则表达式(.NET)不匹配的字符 [英] Replace/Remove characters that do not match the Regular Expression (.NET)

查看:154
本文介绍了替换/删除与正则表达式(.NET)不匹配的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正则表达式来验证字符串.但是现在我想删除所有与我的正则表达式不匹配的字符.

I have a regular expression to validate a string. But now I want to remove all the characters that do not match my regular expression.

例如

regExpression = @"^([\w\'\-\+])"

text = "This is a sample text with some invalid characters -+%&()=?";

//Remove characters that do not match regExp.

result = "This is a sample text with some invalid characters -+";

关于如何使用RegExpression确定有效字符并删除所有其他字符的任何想法.

Any ideas of how I can use the RegExpression to determine the valid characters and remove all the other ones.

非常感谢

推荐答案

我相信您可以在一行中做到这一点(白名单字符并替换所有其他字符):

I believe you can do this (whitelist characters and replace everything else) in one line:

var result = Regex.Replace(text, @"[^\w\s\-\+]", "");

从技术上讲,它将产生以下内容: 这是带有一些无效字符的示例文本-+" 这与您的示例(-和+之间的多余空格)稍有不同.

Technically it will produce this: "This is a sample text with some invalid characters - +" which is slightly different than your example (the extra space between the - and +).

这篇关于替换/删除与正则表达式(.NET)不匹配的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆