允许在C#中使用反斜杠的正则表达式 [英] Regular expression to allow backslash in C#

查看:534
本文介绍了允许在C#中使用反斜杠的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以给我提供用于验证字符串的正则表达式,该表达式只允许除反斜杠之外的任何特殊字符。我尝试过

Can anyone provide me with regex for validating string which only should not allow any special characters except backslash. I tried

var regexItem = new Regex("^[a-zA-Z0-9\\\ ]*$");

但这似乎不起作用

推荐答案

反斜杠需要在正则表达式中转义-并且 也需要在C#中转义,除非您使用 verbatim字符串文字。因此,其中任何一个都应该起作用:

Backslashes need to be escaped in regular expressions - and they also need to be escaped in C#, unless you use verbatim string literals. So either of these should work:

var regexItem = new Regex(@"^[a-zA-Z0-9\\ ]*$");
var regexItem = new Regex("^[a-zA-Z0-9\\\\ ]*$");

这两个都确保将以下字符串内容传递给 Regex 构造函数:

Both of these ensure that the following string content is passed to the Regex constructor:

^[a-zA-Z0-9\\ ]*$

然后, Regex 代码将看到双反斜杠和将其视为我真的想匹配反斜杠字符。

The Regex code will then see the double backslash and treat it as "I really want to match the backslash character."

基本上,您始终需要区分要传递给正则表达式引擎的字符串内容和源代码中的字符串文字表示形式。 (当然,这不仅适用于正则表达式。调试器无法通过在Watch窗口等处转义来提供帮助。)

Basically, you always need to distinguish between "the string contents you want to pass to the regex engine" and "the string literal representation in the source code". (This is true not just for regular expressions, of course. The debugger doesn't help by escaping in Watch windows etc.)

编辑:现在,问题已经出炉了。编辑以显示您最初有三个反斜杠,那只是无效的C#。我怀疑,您的目标是其中包含三个反斜杠的字符串:

Now that the question has been edited to show that you originally had three backslashes, that's just not valid C#. I suspect you were aiming for "a string with three backslashes in" which would be either of these:

var regexItem = new Regex(@"^[a-zA-Z0-9\\\ ]*$");
var regexItem = new Regex("^[a-zA-Z0-9\\\\\\ ]*$");

...但是就正则表达式而言,您无需转义空格

... but you don't need to escape the space as far as the regular expression is concerned.

这篇关于允许在C#中使用反斜杠的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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