Regex Apostrophe how to match?

后端 未结 2 648
北荒
北荒 2021-01-19 08:16

I want to add to this rule match on Apostrophe \'

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

I have tried:

2条回答
  •  耶瑟儿~
    2021-01-19 08:54

    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
    

提交回复
热议问题