在正则表达式中,什么是回溯/回溯引用? [英] In regular expressions, what is a backtracking / back referencing?

查看:51
本文介绍了在正则表达式中,什么是回溯/回溯引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用正则表达式回溯是什么意思?

What does it mean to use a regular expression backtracking?

另外,你能举个例子吗?

Also, could you provide an example of this?

推荐答案

反向引用和回溯是两件不同的事情.前者在代码中稍后使用捕获的结果,例如

Backreferences and backtracking are two different things. The former is using the results of a capture later in code, e.g.

(['"]).*?\1

这将匹配单引号或双引号字符串(暂时忽略转义).它使用反向引用来引用打开符号(单引号或双引号),以便在末尾匹配.

This will match a single- or double-quoted string (ignoring escapes for the moment). It uses a backreference to refer to the open symbol (the single or double quote) so it can match that at the end.

另一方面,回溯是当匹配失败时正则表达式在匹配过程中自然做的事情.例如,如果我匹配表达式

Backtracking, on the other hand, is what regular expressions do naturally during the course of matching when a match fails. For example, if I'm matching the expression

.+b

针对字符串

aaaaaabcd

然后它将首先匹配 .+ 上的 aaaaaabc 并将 b 与剩余的 d 进行比较.这失败了,所以它会回溯一点并为 .+ 匹配 aaaaaab,然后将最终的 b 与 c.这也失败了,所以它再次回溯并为 .+ 尝试 aaaaaa 并将 bb 匹配> 并成功.

then it will first match aaaaaabc on the .+ and compare b against the remaining d. This fails, so it backtracks a bit and matches aaaaaab for the .+ and then compares the final b against the c. This fails too, so it backtracks again and tries aaaaaa for the .+ and the matches the b against the b and succeeds.

这篇关于在正则表达式中,什么是回溯/回溯引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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