正则表达式匹配不完成 [英] Regex matching doesn't finish

查看:78
本文介绍了正则表达式匹配不完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一次回答了关于使用转义引号匹配带引号的字符串的问题。

I've once answered a question about matching a quoted string with escaped quotes.

似乎还有一些挂在.NET和崩溃对单情况下( OutOfMemoryException异常),例如:

It seems that there are cases that hang on .NET and crash on Mono (with OutOfMemoryException), for example:

var reg = new Regex(@"^""([^\\""]*(\\"")*(\\[^""])*)*""");
reg.Match("\"                               ");

两个问题:

1)为什么会发生这种情况?

1) why does this happen?

2)如何改善这个正则表达式?我希望它preserve所有的功能。

2) how to improve this regex? I want it to preserve all the "features".

推荐答案

这的确是(CF添S.)一个灾难性的回溯与这部分你的模式:(\\ [^] )*)* ,允许一切可能的世界,并导致正则表达式引擎来尝试了太多的可能性。 (插图更好一点可以,如果你跟着添S.链接找到)

It is indeed (cf Tim S.) a catastrophic backtracking with this part of your pattern: (\\[^""])*)* which allows all that is possible in the world and cause the regex engine to try too many possibilities. (Better illustrations can be found if you follow Tim S. link)

这是其他模式来做到这一点:

An other pattern to do this:

var reg = new Regex(@"(?s)""(?>[^\\""]+|\\{2}|\\.)*""");

(这样做是为了匹配所有偶数反斜线的(交替的第二部分)之前,一定要允许的实际转义字符的交替(第三部分)

这篇关于正则表达式匹配不完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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