How to Determine if Python Regular Expression Contains ' (Single Quote)

Asked 2 years ago, Updated 2 years ago, 363 views

You are using Python to create a program that verifies that the file name is as specified.
Regular expressions are used to verify that the file name is as specified.
"$" and "-" were able to pattern regular expressions by adding escape characters (\).
How do I specify a single quotation?

Created Programs

import re
strFileName = "Check'XXX.tar.gz"

Reg=re.compile(r'^[a-zA-Z0-9\$-\.]+$')

p=Reg.match(strFileName)
if (pis None):
    print("False")
else:
    print("True")

python python3 regular-expression

2022-09-30 22:05

2 Answers

No escape is required when dealing with single quotation in regular expressions.
However, python needs to escape like \' when you have the entire string 'single quotation'.

As a prerequisite,

"$" and "-" were able to pattern regular expressions by adding escape characters ().

The program you are questioning does not escape - .
In this case, ' between $ and . on the character code is also included in the regular expression range, which may be the reason.

sample code

import re
strFileName = "Check'XXX.tar.gz" 

ifre.match(r'^[a-zA-Z0-9\$-\.]+$',strFileName):
    print("'Single Quotation' is also within range as we have specified $-.($ to $.)")

ifre.match(r'^[a-zA-Z0-9\$\-\.]+$',strFileName):
    print("Only $ and - and . are specified, so 'single quotation' is out of range")

ifre.match(r"^[a-zA-Z0-9\$\-\.']+$",strFileName):#Simply 'single quotation' is OK when the entire string is "double quotation"
    print("'Single Quotation' is in range' because $ and - and . and ' are specified")

ifre.match(r'^[a-zA-Z0-9\$\-\.\']+$',strFileName):# Escape with \'single quotation\' when you are tying the entire string with 'single quotation'
    print("Single Quotation" is in range (same syntax as above) because $ and - and . and ' are specified)")

Run Results

 $-. (from $ to .) so 'single quotation' is also within the range
'Single Quotation' is within range because $ and - and . and ' are specified
'Single quotation' is in range (same syntax as above) because $ and - and . and ' are specified


2022-09-30 22:05

' shouldn't have any special meaning, so I think you just type it in.

If you can't distinguish (it doesn't work) from the single quote in compile(r'...') when specifying the pattern, try changing it to a double quote.

compile(r"^[a-zA-Z0-9\$-\.']+$")

By the way, $ has a special meaning only when it appears at the end of the line of the pattern. I don't think you need to escape within [].


2022-09-30 22:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.