简体   繁体   English

如何检查正则表达式是否永远匹配?

[英]How can I check if a regex matches forever?

I need a way to check if a regex can match 0 characters, and therefore matches infinitely. 我需要一种方法来检查正则表达式是否可以匹配0个字符,因此可以无限匹配。 For example, the regex .* can match 0 characters which means that it will loop for ever, crashing my app. 例如,正则表达式.*可以匹配0个字符,这意味着它将永远循环,从而使我的应用程序崩溃。

In my app, the user inputs a regex, which can of course loop forever. 在我的应用程序中,用户输入一个正则表达式,它当然可以永远循环。 How can I prevent this happening? 如何防止这种情况发生?

There is no such thing as a regex matching infinitely; 没有正则表达式可以无限匹配的东西。 thus being stuck in an infinite loop. 因此陷入无限循环。 As an example, the regex .* will stop immediately when there are 0 characters and will run for n iterations on any string of n characters. 例如,当有0个字符时,正则表达式.*将立即停止,并且将在n n字符的任何字符串上运行n次迭代。

A regex is a form of a finite state machine. 正则表达式是有限状态机的一种形式。 A string, its input, is also always finite. 字符串(其输入)也始终是有限的。 There is no infinite in regular expressions. 正则表达式中没有无限。

Here is a the same question asked in a CS context: https://cs.stackexchange.com/questions/47835/can-a-regular-expression-be-infinite 这是在CS上下文中询问的相同问题: https : //cs.stackexchange.com/questions/47835/can-a-regular-expression-be-infinite

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM