Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.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中删除url的一部分?_Python_Regex - Fatal编程技术网

如何在python中删除url的一部分?

如何在python中删除url的一部分?,python,regex,Python,Regex,我有一个URL列表,在&符号后面的末尾有不同的数字。我无法应用正则表达式从url中删除这些数字(包括&),因为字符串中有多个&并且re.sub(“&\d*”,“”,x)命令过滤所有&,包括我要删除的数字 url是:http://helloworld.com?p1=123&p2=987&hello=world&123456 我想要的输出是:http://helloworld.com?p1=123&p2=987&hello=world您需要+在\d之后进行匹配!使用&\d*时,它首先匹配中间的&。此

我有一个URL列表,在
&
符号后面的末尾有不同的数字。我无法应用正则表达式从url中删除这些数字(包括
&
),因为字符串中有多个&并且
re.sub(“&\d*”,“”,x)
命令过滤所有
&
,包括我要删除的数字

url是:
http://helloworld.com?p1=123&p2=987&hello=world&123456


我想要的输出是:
http://helloworld.com?p1=123&p2=987&hello=world

您需要
+
\d
之后进行匹配!使用
&\d*
时,它首先匹配中间的
&
。此外,您还需要一个
$
来指定您的模式位于字符串的末尾:

'http:\\helloworld.com?p1=123&p2=987&hello=world&123456'
                             ^

因此,请使用
re.sub(r'(&\d+)$,“”,x)
而不是您的!请参阅。

您需要在
\d
之后添加
+
才能匹配!使用
&\d*
时,它首先匹配中间的
&
。此外,您还需要一个
$
来指定您的模式位于字符串的末尾:

'http:\\helloworld.com?p1=123&p2=987&hello=world&123456'
                             ^

因此,请使用
re.sub(r'(&\d+)$,“”,x)
而不是您的!请参阅。

如果始终需要最后一个参数,则可以使用锚定模式:

re.sub(r'&\d+$',"",x)
最重要的是美元符号,上面写着“只在最后匹配”


您还应该记住,无论何时使用
*
,都可以匹配空字符串。如果要匹配非空字符串,则需要使用
+

如果始终需要最后一个参数,则可以使用锚定模式:

re.sub(r'&\d+$',"",x)
最重要的是美元符号,上面写着“只在最后匹配”


您还应该记住,无论何时使用
*
,都可以匹配空字符串。如果要匹配非空字符串,你需要使用<代码> +<代码> < /p> @ Kasra。你的答案是错误的,因为你仍然可以在字符串中间匹配某个东西。@ Kasra你的答案是错误的,因为你仍然可以在字符串中间匹配某个东西。一般来说,在使用<代码> R′<代码>指定正则表达式时最好使用原始字符串。字符串当使用
r''
指定正则表达式时,我想您的意思是在URL中使用前斜杠,如
http://
而不是后斜杠。另外,我想您的意思是在URL中使用前斜杠,如
http://
而不是后斜杠。