正则表达式跳过某些字符Regex to skip certain characters

- 此内容更新于:2015-01-06
主题:

原文:

I want to write a Regex which would skip characters like < & >. Reason

Now, to represent this I came across this [^<>] and tried using it in an console application, but it does not work.

[^<>]

Regular expression visualization

Debuggex Demo

string value = "shubh<";
string regEx = "[^<>]";
Regex rx = new Regex(regEx);

if (rx.IsMatch(value))
{
    Console.WriteLine("Pass");
}
else { Console.WriteLine("Fail"); }
Console.ReadLine();

The string 'shubh<' should get failed, but I am not sure why it passes the match. Am I doing something rubbish?

Bryan Oakley的回复:你的问题是什么?

(原文:what is your question?)

Shubh的回复:如何禁用& lt;在。抱歉的混乱。

(原文:How to only disable < & >. Sorry for the confusion.)

Bryan Oakley的回复:你的问题给出了答案:匹配除了& lt;调整;[^ & lt;调整;]模式匹配这两个字符。再次,你问,因为你似乎已经知道这个模式吗?

(原文:Your question shows the answer: to match anything except < and >, the pattern [^<>] matches anything but those two characters. Again, what are you asking, since you already seem to know about this pattern?)

Shubh的回复:是的,这是正确的实现吗?这就是我想确认。

(原文:Yep, Is that correct to implement? Thats what I wanted to confirm.)

Shubh的回复:@BryanOakley,我已经更新了的问题。我在在c#中,这并不工作。抱歉的混乱。

(原文:@BryanOakley, I have updated the question. I am trying in C# and this does not work. Sorry for the confusion.)

解决方案:
原文:

From Regex.IsMatch Method (String):

Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.

[^<>] is found in shubh< (the s, the h, etc.).

You need to use the ^ and $ anchors:

Regex rx = new Regex("^[^<>]*$");
if (rx.IsMatch(value)) {
    Console.WriteLine("Pass");
} else {
    Console.WriteLine("Fail");
}

Another solution is to check if < or > is contained:

Regex rx = new Regex("[<>]");
if (rx.IsMatch(value)) {
    Console.WriteLine("Fail");
} else {
    Console.WriteLine("Pass");
}
Shubh的回复:感觉严重有罪! ! !(我怎么能忽略这一点。谢谢你指出了其中的不足。

(原文:Feeling seriously guilty!!! :( How could I ignore that. Thanks for pointing that out.)