Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In regular expressions, what is a backtracking / back referencing?

Tags:

regex

What does it mean to use a regular expression backtracking?

Also, could you provide an example of this?

like image 255
chrisjlee Avatar asked Jan 25 '12 22:01

chrisjlee


People also ask

What does this mean in regex ([ ])\ 1?

The \1 in a regex like (a)[\1b] is either an error or a needlessly escaped literal 1. In JavaScript it's an octal escape.

What is returned by the regular expression search method?

The search() method searches through a string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object.

How do I reference a capture group in regex?

If your regular expression has named capturing groups, then you should use named backreferences to them in the replacement text. The regex (?' name'group) has one group called “name”. You can reference this group with ${name} in the JGsoft applications, Delphi, .

What is the question mark in regex?

A question mark ( ? ) immediately following a character means match zero or one instance of this character . This means that the regex Great!? will match Great or Great! .


1 Answers

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 

against the string

aaaaaabcd 

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.

like image 117
Lily Ballard Avatar answered Oct 11 '22 12:10

Lily Ballard