正则撇号怎么匹配? [英] Regex Apostrophe how to match?
本文介绍了正则撇号怎么匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 撇号 '
rule = re.compile(r'^[^*$<,>?!]*$')
我试过了:
rule = re.compile(r'^[^*$<,>?!']*$')
但它认为撇号是行错误,为什么?
解决方案
出现错误是因为你不能直接在 ''
中使用单个 '
和类似的单个 "
不能在 ""
内使用,因为这会混淆 python,现在它不知道字符串实际结束的位置.
您可以使用双引号或使用 '\'
转义单引号:
rule = re.compile(r"^[^*$<,>?!']*$")
演示:
<预><代码>>>>strs = '不能'>>>打印字符串不能>>>strs = "不能">>>打印字符串不能>>>'不能'#wrong,SyntaxError:无效语法>>>"can"t" #wrong, SyntaxError: 无效语法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?
解决方案
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
这篇关于正则撇号怎么匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文