gpt4 book ai didi

python - Pandas :试图提取两种不同的模式

转载 作者:太空宇宙 更新时间:2023-11-04 01:44:51 25 4
gpt4 key购买 nike

要从我正在使用的字符串中提取特定数字:

df['URL'].str.extract(r'dir=sale.aspx\%3fvpid%\w{2}(\d+)\%*',expand=False)

字符串示例:

'a'|'b'|'c'|'d|'0CCC63BF60D2&dir=sale.aspx%3fvpid%3d49398%26utm_source%xyz'|'e'

这里我要提取:49398

我必须在相同的代码中为这种字符串提取第二个模式:

'a'|'b'|'c'|'d'|'6A5528CD54F4&dir=sale.aspx&vpid=66395&utm_source=abc'|'a'

这里我要提取:66395

我需要使用一些尝试两种不同模式的东西。

我正在使用 python 2,7

最佳答案

你可以试试这个模式:

pattern = r'dir=sale.aspx(?:\%3fvpid%\w{2}|\&vpid=)(\d+)\%*'

# test data
df = pd.DataFrame({"URL":[
"'a'|'b'|'c'|'d|'0CCC63BF60D2&dir=sale.aspx%3fvpid%3d49398%26utm_source%xyz'|'e'",
"'a'|'b'|'c'|'d'|'6A5528CD54F4&dir=sale.aspx&vpid=66395&utm_source=abc'|'a'"
]})

# regex
df.URL.str.extract(pattern)

输出:

       0
0 49398
1 66395

关于python - Pandas :试图提取两种不同的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59288044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com