
* Modify rule S5361: Add Python as covered language * Fix typos in S5361 rule descriptions * Remove wrong delimiters * Rename var and fix comment
33 lines
1.1 KiB
Plaintext
33 lines
1.1 KiB
Plaintext
An `re.sub` call always performs an evaluation of the first argument as a regular expression, even if no regular expression features were used. This has a significant performance cost and therefore should be used with care.
|
|
|
|
|
|
When `re.sub` is used, the first argument should be a real regular expression. If it's not the case, `str.replace` does exactly the same thing as `re.sub` without the performance drawback of the regex.
|
|
|
|
|
|
This rule raises an issue for each `re.sub` used with a simple string as first argument which doesn't contains special regex character or pattern.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
input = "Bob is a Bird... Bob is a Plane... Bob is Superman!"
|
|
changed = re.sub("Bob is", "It's", input) # Noncompliant
|
|
changed = re.sub("\.\.\.", ";", changed) # Noncompliant
|
|
----
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
input = "Bob is a Bird... Bob is a Plane... Bob is Superman!"
|
|
changed = str.replace("Bob is", "It's", input)
|
|
changed = str.replace("...", ";", changed)
|
|
----
|
|
Or, with a regex:
|
|
|
|
----
|
|
input = "Bob is a Bird... Bob is a Plane... Bob is Superman!"
|
|
changed = re.sub(r"\w*\sis", "It's", input)
|
|
changed = re.sub(r"\.{3}", ";", changed)
|
|
----
|