6

I want to add to this rule match on Apostrophe '

rule = re.compile(r'^[^*$<,>?!]*$')

I have tried:

rule = re.compile(r'^[^*$<,>?!']*$')

but it sees the apostrophe as a line error, why?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
GrantU
  • 6,325
  • 16
  • 59
  • 89

2 Answers2

9

You have to escape the apostrophe, otherwise it will be counted as the end of the raw string:

rule = re.compile(r'^[^*$<,>?!\']*$')

Or, you can use " to surround your string, which is perfectly valid in python:

rule = re.compile(r"^[^*$<,>?!']*$")
TerryA
  • 58,805
  • 11
  • 114
  • 143
9

The error comes because you cannot directly use a single ' inside '' and similarly single " can't be used inside "" because this confuses python and now it doesn't know where the string actually ends.

You can use either double quotes or escape the single quote with a '\':

rule = re.compile(r"^[^*$<,>?!']*$")

Demo:

>>> strs = 'can\'t'
>>> print strs
can't
>>> strs = "can't"
>>> print strs
can't
>>> 'can't'  #wrong, SyntaxError: invalid syntax

>>> "can"t"  #wrong, SyntaxError: invalid syntax
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504