ChatGPT解决这个技术问题 Extra ChatGPT

Escaping regex string

I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex?

For example, the user wants to search for Word (s): regex engine will take the (s) as a group. I want it to treat it like a string "(s)" . I can run replace on user input and replace the ( with \( and the ) with \) but the problem is I will need to do replace for every possible regex symbol.

Do you know some better way ?

what is the usual use for this in the context of regexes and matching patterns/capture groups to big strings?
i think my answer explains the principles well: stackoverflow.com/a/73068412/1601580

2
200_success

Use the re.escape() function for this:

4.2.3 re Module Contents

escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.

def simplistic_plural(word, text):
    word_or_plural = re.escape(word) + 's?'
    return re.match(word_or_plural, text)

i dont understand why this has so many upvotes. It doesn't explain why or when we'd want to use the escape...or even mention why raw strings are relevant which imho is important to make sense of when to use this.
N
Neuron

You can use re.escape():

re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'

If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.

If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_).


wouldn't passing a raw string be enough or are you trying to match the literal ^? I usually use re.escape to force it to match things I want matched literally like parens and spaces.
O
Owen

Unfortunately, re.escape() is not suited for the replacement string:

>>> re.sub('a', re.escape('_'), 'aa')
'\\_\\_'

A solution is to put the replacement in a lambda:

>>> re.sub('a', lambda _: '_', 'aa')
'__'

because the return value of the lambda is treated by re.sub() as a literal string.


The repl argument to re.sub is a string, not a regex; applying re.escape to it doesn't make any sense in the first place.
@tripleee That's incorrect, the repl argument is not a simple string, it is parsed. For instance, re.sub(r'(.)', r'\1', 'X') will return X, not \1.
Here's the relevant question for escaping the repl argument: stackoverflow.com/q/49943270/247696
Changed in version 3.3: The '_' character is no longer escaped. Changed in version 3.7: Only characters that can have special meaning in a regular expression are escaped. (Why did it take so long?)
S
Stefano Munarini

The answer of Owen can lead to inconsistencies. A lambda should just be an inline replacement for a function call, but it produces different results as shown below. When somebody would have to 'upgrade' the lambda to a function call, for instance to build in some extra complexity, this would suddenly break down:

import re

xml = """pre@mytag@123@/mytag@post"""

replacewith = '@mytag@456 \\1@/mytag@'

regexp = re.compile(r'@mytag@(.*?)@/mytag@', re.S|re.M|re.I)

def rw(inp):

  return inp

result = regexp.sub(lambda _: replacewith, xml)

print(result) # desired result

result = regexp.sub(rw(replacewith), xml)

print(result) # undesired result

C
Charlie Parker

Usually escaping the string that you feed into a regex is such that the regex considers those characters literally. Remember usually you type strings into your compuer and the computer insert the specific characters. When you see in your editor \n it's not really a new line until the parser decides it is. It's two characters. Once you pass it through python's print will display it and thus parse it as a new a line but in the text you see in the editor it's likely just the char for backslash followed by n. If you do \r"\n" then python will always interpret it as the raw thing you typed in (as far as I understand). To complicate things further there is another syntax/grammar going on with regexes. The regex parser will interpret the strings it's receives differently than python's print would. I believe this is why we are recommended to pass raw strings like r"(\n+) -- so that the regex receives what you actually typed. However, the regex will receive a parenthesis and won't match it as a literal parenthesis unless you tell it to explicitly using the regex's own syntax rules. For that you need r"(\fun \( x : nat \) :)" here the first parens won't be matched since it's a capture group due to lack of backslashes but the second one will be matched as literal parens.

Thus we usually do re.escape(regex) to escape things we want to be interpreted literally i.e. things that would be usually ignored by the regex paraser e.g. parens, spaces etc. will be escaped. e.g. code I have in my app:

    # escapes non-alphanumeric to help match arbitrary literal string, I think the reason this is here is to help differentiate the things escaped from the regex we are inserting in the next line and the literal things we wanted escaped.
    __ppt = re.escape(_ppt)  # used for e.g. parenthesis ( are not interpreted as was to group this but literally

e.g. see these strings:

_ppt
Out[4]: '(let H : forall x : bool, negb (negb x) = x := fun x : bool =>HEREinHERE)'
__ppt
Out[5]: '\\(let\\ H\\ :\\ forall\\ x\\ :\\ bool,\\ negb\\ \\(negb\\ x\\)\\ =\\ x\\ :=\\ fun\\ x\\ :\\ bool\\ =>HEREinHERE\\)'
print(rf'{_ppt=}')
_ppt='(let H : forall x : bool, negb (negb x) = x := fun x : bool =>HEREinHERE)'
print(rf'{__ppt=}')
__ppt='\\(let\\ H\\ :\\ forall\\ x\\ :\\ bool,\\ negb\\ \\(negb\\ x\\)\\ =\\ x\\ :=\\ fun\\ x\\ :\\ bool\\ =>HEREinHERE\\)'

the double backslashes I believe are there so that the regex receives a literal backslash.

btw, I am surprised it printed double backslashes instead of a single one. If anyone can comment on that it would be appreciated. I'm also curious how to match literal backslashes now in the regex. I assume it's 4 backslashes but I honestly expected only 2 would have been needed due to the raw string r construct.


btw, I am surprised it printed double backslashes instead of a single one. If anyone can comment on that it would be appreciated. I'm also curious how to match literal backslashes now in the regex. I assume it's 4 backslashes but I honestly expected only 2 would have been needed due to the raw string r construct.
g
guru

Please give a try:

\Q and \E as anchors

Put an Or condition to match either a full word or regex.

Ref Link : How to match a whole word that includes special characters in regex