42 lines
1.1 KiB
Plaintext
42 lines
1.1 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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[]
|