40 lines
1.0 KiB
Plaintext
40 lines
1.0 KiB
Plaintext
![]() |
When a back reference in a regex refers to a capturing group that hasn't been defined yet (or at all), it can never be matched and will fail with an `re.error` exception
|
||
|
|
||
|
== Noncompliant Code Example
|
||
|
|
||
|
[source,python]
|
||
|
----
|
||
|
import re
|
||
|
pattern1 = re.compile(r"\1(.)") # Noncompliant, group 1 is defined after the back reference
|
||
|
pattern2 = re.compile(r"(.)\2") # Noncompliant, group 2 isn't defined at all
|
||
|
pattern3 = re.compile(r"(.)|\1") # Noncompliant, group 1 and the back reference are in different branches
|
||
|
pattern4 = re.compile(r"(?P<x>.)|(?P=x)") # Noncompliant, group x and the back reference are in different branches
|
||
|
----
|
||
|
|
||
|
|
||
|
== Compliant Solution
|
||
|
|
||
|
[source,python]
|
||
|
----
|
||
|
import re
|
||
|
pattern1 = re.compile(r"(.)\1")
|
||
|
pattern2 = re.compile(r"(?P<x>.)(?P=x)")
|
||
|
----
|
||
|
|
||
|
ifdef::env-github,rspecator-view[]
|
||
|
|
||
|
'''
|
||
|
== Implementation Specification
|
||
|
(visible only on this page)
|
||
|
|
||
|
include::../message.adoc[]
|
||
|
|
||
|
include::../highlighting.adoc[]
|
||
|
|
||
|
'''
|
||
|
== Comments And Links
|
||
|
(visible only on this page)
|
||
|
|
||
|
include::../comments-and-links.adoc[]
|
||
|
endif::env-github,rspecator-view[]
|