我昨天做了评论,其中有人曾用一个答案[0123456789]的正则表达式,而不是[0-9]或\d.我说使用范围或数字说明符比使用字符集更有效.
我决定今天测试一下,并且我惊讶地发现(至少在C#正则表达式引擎中)\d似乎效率低于其他两个似乎没有太大差别的.这是我的10000个随机字符串1000个随机字符的测试输出,其中5077实际上包含一个数字:
Regular expression \d took 00:00:00.2141226 result: 5077/10000
Regular expression [0-9] took 00:00:00.1357972 result: 5077/10000 63.42 % of first
Regular expression [0123456789] took 00:00:00.1388997 result: 5077/10000 64.87 % of first
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是有两个原因:
\d会比这更糟糕[0-9].还有\d简单的简写[0-9]吗?这是测试代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace SO_RegexPerformance
{
class Program
{
static void Main(string[] args)
{
var rand = new …Run Code Online (Sandbox Code Playgroud) 昨天我有一个任务是在用户可以输入他想要下载的页面范围的字段上实现验证.
在阅读了一些教程之后,我创建了这样的模式,在我看来应该可行,但它没有:(
你能否给我一个提示,说明错误在哪里,或者以更好的方式完成.
<script type="text/javascript">
var patt1=new RegExp("^(\s*\d+\s*\-\s*\d+\s*,?|\s*\d+\s*,?)+$");
document.write(patt1.test("1, 2, 3-5, 6, 8, 10-12"));
</script>
Run Code Online (Sandbox Code Playgroud)
PS你可以在这里测试一下:http://www.w3schools.com/js/tryit.asp?filename = tryjs_regexp_test
更多例子:
等......就像在MS Office或Adobe PDF Reader中一样