Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

regex - How to escape “” characters in python

i am very new to regular expression and trying get "" character using python

normally i can escape "" like this

print ("");
print ("i am \nit");

output


i am 
it

but when i use the same in regX it didn't work as i thought

print (re.findall(r'\',"i am \nit"));

and return me output

['\']

can someone please explain why

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

EDIT: The problem is actually how print works with lists & strings. It prints the representation of the string, not the string itself, the representation of a string containing just a backslash is '\'. So findall is actually finding the single backslash correctly, but print isn't printing it as you'd expect. Try:

>>> print(re.findall(r'\',"i am \nit")[0])


(The following is my original answer, it can be ignored (it's entirely irrelevant), I'd misinterpreted the question initially. But it seems to have been upvoted a bit, so I'll leave it here.)

The r prefix on a string means the string is in "raw" mode, that is, are not treated as special characters (it doesn't have anything to do with "regex").

However, r'' doesn't work, as you can't end a raw string with a backslash, it's stated in the docs:

Even in a raw string, string quotes can be escaped with a backslash, but the backslash remains in the string; for example, r""" is a valid string literal consisting of two characters: a backslash and a double quote; r"" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character).

But you actually can use a non-raw string to get a single backslash: "".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...