python - r'string'和python中的普通 'string'有什么区别?

标签 python regex string

python 中的 r 字符串 (r'foobar') 和普通字符串 ('foobar') 有什么区别? r'string' 是正则表达式字符串吗?

我已经尝试了以下方法,但对我的正则表达式匹配没有任何影响:

>>> import re
>>> n = 3
>>> rgx = '(?=('+'\S'*n+'))'
>>> x = 'foobar'
>>> re.findall(rgx,x)
['foo', 'oob', 'oba', 'bar']
>>>
>>> rgx2 = r'(?=('+'\S'*n+'))'
>>> re.findall(rgx2,x)
['foo', 'oob', 'oba', 'bar']
>>>
>>> rgx3 = r'(?=(\S\S\S))'
>>> re.findall(rgx3,x)
['foo', 'oob', 'oba', 'bar']

最佳答案

r 并不表示“正则表达式字符串”;它的意思是“原始字符串”。根据 the docs :

String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.

它们通常用于(和 recommended )用于正则表达式,因为正则表达式和非原始字符串使用反斜杠作为转义字符。例如,要将文字反斜杠与普通字符串中的正则表达式相匹配,将是 '\\\\';使用原始字符串,它只是 '\\'

关于python - r'string'和python中的普通 'string'有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22429505/

相关文章:

python - 通过从固定的常量日期时间偏移以秒为单位的间隔来获取新的日期时间

python - python中不带括号的与带括号的 'for loop'之间的区别?

python - 限制 Django Tastypie 中嵌套资源的数量?

python - 从 MLab 迭代 pymongo 游标

javascript - 将输入字符串与文本/元素匹配并突出显示 react 性

c# - 在数学回合中使用 'double' 中的逗号

java - Java 中动态缩进字符串

javascript - jquery regexp - 正则表达式

regex - 列出 R 中不匹配模式的文件

c++ - 'itoa' : function does not take 1 arguments & 'c' : undeclared identifier