Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么不';这两个正则表达式(一个带变量)等价吗?_Python_Regex - Fatal编程技术网

Python 为什么不';这两个正则表达式(一个带变量)等价吗?

Python 为什么不';这两个正则表达式(一个带变量)等价吗?,python,regex,Python,Regex,这是原始的正则表达式,可以很好地工作: regex = r"(https:\/\/www\.snopes+...+?)(&)" matches = re.findall(regex, soup, re.MULTILINE) 我决定用一个变量替换“snopes”,因此我创建了以下变量,但它不起作用: fact_checker = "snopes" regex1 = 'r"(https:\/\/www\.' regex2 = '+...+?)(&)"'

这是原始的正则表达式,可以很好地工作:

regex = r"(https:\/\/www\.snopes+...+?)(&)"
matches = re.findall(regex, soup, re.MULTILINE)
我决定用一个变量替换“snopes”,因此我创建了以下变量,但它不起作用:

    fact_checker = "snopes"

    regex1 = 'r"(https:\/\/www\.'

    regex2 = '+...+?)(&)"'

    regex3 = regex1 + fact_checker + regex2

    matches = re.findall(regex3, soup, re.MULTILINE)
regex和regex3怎么不一样?当我把它们打印出来时,它们看起来是一样的

我想出来了:

regex1 = r"(https:\/\/www\."

regex2 = r"+...+?)(&)"

regex3 = regex1 + fact_checker + regex2

假设
r
前缀是值的一部分,这是一个非常常见的错误。事实并非如此;它只是告诉Python解释器在下面的字符串中使用了哪种类型的引号。(可能与
0.0L
在C中是一个数字相比;
L
后缀表示它是一个存储类型
long
的数字)

无论如何,做你想做的事情的惯用方法是

regex = r"(https://www\.{}+...+?)(&)".format(fact_checker)

(斜杠在正则表达式中没有特殊意义,所以我去掉了多余的反斜杠。正则表达式毫无疑问仍然可以改进。)

regex1='r'(https:\/\/www\。
在字符串中放入一个文本
r
*和
)字符。对不起,这是什么语言?请把它贴上标签such@CertainPerformance这是有道理的。由于
作为转义字符使用,因此很难在其后插入变量。我试着玩弄它,但没弄明白。@billynoah我的错,它是用Python写的。你真的想让正则表达式匹配
snopes
snopess
snopess
,等等吗?这就是加号的作用。这比我的解决方案要简洁得多。谢谢