C# 简单正则表达式 - 32 个字符,仅包含 0-9 和 af (GUID)
如何在 C# 中使用正则表达式进行测试:
- 字符串长度恰好为 32
- 字符串仅包含 0-9 的数字和 af 的小写字母
How to test using regex in C# if:
- length of string is exactly 32
- string contains only numbers from 0-9 and small letters from a-f
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
怎么样:
How about:
在 .Net 4.0 中,有一个
Guid
结构,它具有TryParse
静态函数。http://msdn.microsoft.com/en-us/library/system .guid.aspx
In .Net 4.0 there is
Guid
structure that hasTryParse
static function.http://msdn.microsoft.com/en-us/library/system.guid.aspx
如果您不打算使用正则表达式来实现此目的,那么这非常干净:
If you're not dead-set on using a Regex for this purpose, this is pretty clean:
好的,这里有一个答案向您展示如何确定该字符串的长度是否为 32 个字符,并且每个字符要么是数字,要么是小写“a”到小写“f”,并使用正则表达式,另一个答案向您展示了如何使用一个简单的 Func 来扫描字符串中的字符。它们都是很好的答案,并且在技术上是正确的,但是在您的问题标题中,您明确指出了“GUID”,这打开了新的蠕虫罐头。
GUID 可以采用多种不同的字符串表示形式,您可能会遇到其中任何一种。您需要处理所有这些吗?您是否需要容纳以大括号(“{”和“}”)或圆括号开头和结尾的字符串?破折号('-')呢? 根据 MSDN,创建一个新的 GUID,并
允许使用以下字符串形式
您需要处理所有这些情况吗?另外,请考虑使用正则表达式是否真的是最好的选择。正如一些人已经评论的那样,正则表达式可能会让一些开发人员感到困惑,而且意图并不总是明确的。最重要的是,在某些情况下,正则表达式可能会慢。
我对三种不同的方法进行了快速性能测试,以确定字符串是否实际上是 GUID 的字符串表示形式:
这是代码:
[测试]
在我的机器上进行一百万次迭代的结果:
因此,正则表达式解决方案很慢。问问自己是否真的需要一个正则表达式。请注意,您可能可以通过仅声明一次正则表达式并重用它来获得一些额外的性能,但我认为这种情况下的要点是,通过查看您正在做什么,您可能会取得更好的成功尝试完成,而不是如何。
希望有帮助。
Ok, so there's an answer here that shows you how to find out if this string is 32 characters in length, and each character is either a digit or lowercase 'a' to lowercase 'f' with a regex, and another that shows you how to do it with a simple Func which scans that characters in the string. They're both great answers and technically correct, but in your question title you explicitly state "GUID" which opens up a new can of worms.
GUIDs can take a number of different string representations, and you might encounter any one of them. Do you need to handle all of these? Will you need to accomodate strings that begin and end with curly braces ('{' and '}') or parentheses? What about dashes ('-')? According to MSDN, creating a new GUID with
Allows for strings in the following forms
Do you need to handle all of these cases? Also, consider if using a regex is really the best option. As some people have already commented, regex can be confusing for some developers, and the intent isn't always clear. On top of that, regex can be slow in some cases.
I whipped up a quick performance test on three different ways of determining if a string is in fact a string representation of a GUID:
Here's the code:
[Test]
And the results from a million iterations on my machine:
So, the regex solution is slow. Ask yourself if you really need a regex here. Note that you can probably eek out some extra performance by only declaring the regex once, and reusing it, but I think the point in this case is that you might have better success by looking at what you're trying to accomplish, as opposed to how.
Hope that helps.