在网上正则表达式测试仪,但不是在.NET正则表达式的作品 [英] regex works in online regex tester but not in .NET

查看:165
本文介绍了在网上正则表达式测试仪,但不是在.NET正则表达式的作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下演示工作得很好,在网上而不是当我尝试在C#中运行它/ .NET

the following demo works just fine online but not when I attempt to run it in c#/.NET

 var regex = new RegularExpressionAttribute(@"@(?!.*?\.\.)[^@]+$");
 Assert.IsTrue(regex.IsValid("bob@bob.com"));



这里是一个的链接后,将解释正则表达式和我所试图做的。

here is a link to post that will explain the regex and what I am trying to do

推荐答案

RegularExpressionAttribute 需要字符串的全场比赛。

The RegularExpressionAttribute requires a full match of the string.

在你的情况,你只匹配开始于 @ 字符,让你在你的字符串之间的某处开始。这是RegularExpressionAttribute足够刚不好。你可以把它加入一个隐含的 ^ 在开始你的表达(和隐 $ 结尾太,这样就可以把那个一样)。

In your case, you are only matching starting at the @ character, so you start somewhere in between of your string. This is just not good enough for the RegularExpressionAttribute. You can think of it adding an implicit ^ at the start to your expression (and an implicit $ at the end too, so you can drop that as well).

因此,要解决这个问题,你需要确保它有一些匹配的开始,例如:一个 *

So to fix this, you need to make sure that it has something to match at the start to, e.g. a .*?:

new RegularExpressionAttribute(@".*?@(?!.*?\.\.)[^@]+");

然后它的作品。你不需要任何其他的正则表达式标志。

And then it works. You don’t need any other regular expression flags.

不幸的是,这种行为 RegularExpressionAttribute 在文档中提到无门。您可以在参考源然而验证:

Unfortunately, this behavior of RegularExpressionAttribute is mentioned nowhere in the documentation. You can verify it in the reference source however:

// We are looking for an exact match, not just a search hit. This matches what
// the RegularExpressionValidator control does
return (m.Success && m.Index == 0 && m.Length == stringValue.Length);



所以它在技术上不是一个额外的 ^ $ 但找到一个匹配后,开始和结束索引都需要匹配字符串的开始和结束指数(基本上是同样的事情)。

So it’s technically not an added ^ and $ but after finding a match, the start and end index are required to match the string’s start and end index (which is essentially the same thing).

如果你仔细想想,这种行为使得验证有很大的意义。毕竟,你要确保一个字符串匹配一定全指定的格式,而不是只检查一些子是有效的。

And if you think about it, this behavior makes a lot of sense for validation. After all, you want to make sure that a string matches a certain full-specified format, and not just check if some substring is valid.

这篇关于在网上正则表达式测试仪,但不是在.NET正则表达式的作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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