高效正则表达式的构建与优化
1. 不同语言的正则表达式基准测试
1.1 Ruby 基准测试
以下是 Ruby 中的基准测试示例代码:
TimesToDo = 1000
testString = ""
for i in 1..1000
testString += "abababdedfg"
end
Regex1 = Regexp::new("ˆ(a;b;c;d;e;f;g)+$")
Regex2 = Regexp::new("ˆ[a-g]+$")
startTime = Time.new.to_f
for i in 1..TimesToDo
Regex1.match(testString)
end
print "Alternation takes %.3f seconds\n" % (Time.new.to_f - startTime)
startTime = Time.new.to_f
for i in 1..TimesToDo
Regex2.match(testString)
end
print "Character class takes %.3f seconds\n" % (Time.new.to_f - startTime)
在测试系统中,运行结果为:
| 正则表达式类型 | 耗时(秒) |
| ---- | ---- |
| 交替匹配(Alternation) | 16.311 |
| 字符类匹配(Character class) | 3.479 |
超级会员免费看
订阅专栏 解锁全文
70

被折叠的 条评论
为什么被折叠?



