Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.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中re.sub()的问题_Python_Regex - Fatal编程技术网

关于python中re.sub()的问题

关于python中re.sub()的问题,python,regex,Python,Regex,我想将如下字符串替换为“css/login.css”“***css/login.css***”,整个字符串如下: str1 = '<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0,user-scalable=0">\ <link rel = "stylesheet" type = "text/css" href = "css/login.css"/>

我想将如下字符串替换为
“css/login.css”
“***css/login.css***”,整个字符串如下:

str1 = '<meta name="viewport" content="width=device-width,
initial-scale=1.0,maximum-scale=1.0,user-scalable=0">\
<link rel = "stylesheet" type = "text/css" href = "css/login.css"/>\
<script type="text/javascript" src="js/jquery.js"></script>\
<script type="text/javascript" src="js/login.js"></script>\
<script type="text/javascript" src="js/authLogin.js"></script>\
</head>'

为什么它不在
“css/login.css”/>
之前输出字符串,也就是说
'\如果您希望在输出中再现第一个捕获组之前的部分,那么您也需要为此创建一个捕获组。类似地,对于后面的部分,您可以创建一个捕获组(但是删除惰性的

如果输入字符串中有换行符,则还应使用
re.DOTALL
标志,以便这些换行符与您的
*
匹配:

pattern1 = r'(.*?href.*?=.*?)(".+?\.css")(.*)'
re.sub(pattern1, r"\1***\2***\3", str1, 0, re.DOTALL)

如果希望在输出中再现第一个捕获组之前的零件,则还需要为此创建一个捕获组。类似地,对于后面的部分,您可以创建一个捕获组(但是删除惰性的

如果输入字符串中有换行符,则还应使用
re.DOTALL
标志,以便这些换行符与您的
*
匹配:

pattern1 = r'(.*?href.*?=.*?)(".+?\.css")(.*)'
re.sub(pattern1, r"\1***\2***\3", str1, 0, re.DOTALL)
在中,函数re.sub描述如下:

Return the string obtained by replacing the leftmost non-overlapping occurrences of
pattern in string by the replacement repl.
在正则表达式中,第一个
*
与字符串中
href
前面的所有内容匹配。然后,字符串中包括
“css/login.css”
的所有内容都是您用正则表达式指定的模式的一部分。 然后,在函数re.sub中,将其替换为
***“css/login.css”***

,如下所述:

Return the string obtained by replacing the leftmost non-overlapping occurrences of
pattern in string by the replacement repl.
在正则表达式中,第一个
*
与字符串中
href
前面的所有内容匹配。然后,字符串中包括
“css/login.css”
的所有内容都是您用正则表达式指定的模式的一部分。 然后将其替换为
***“css/login.css”***