繁体   English   中英

正则表达式:从URL中提取特定值

[英]Regex: Extract specific value from URL

我在使用re库从URL精确提取字符串时遇到了一些麻烦。

这是一个例子:

http://www.example.it/remoteconnexion.aspx?u=xxxxx@abc.it&direction=vente.aspx%3pid%xx123%63abcd"

我有一个数据框,我想使用另一列中的值添加一列,在此示例中df ['URL_REG']包含:'123'?

df['URL_REG'] = df['URL'].map(lambda x : re.findall(r'[REGEX]+', x)[0])

URL的结构可以更改,但是我想要的部分始终位于“ direction = vente.aspx%3pid%”和“%”之间。

使用向量化Series.str.extract()方法:

In [50]: df['URL_REG'] = df.URL.str.extract(r'direction=vente.aspx\%3pid\%([^\%]+)\%*',
                                            expand=False)

In [51]: df
Out[51]:
                                                 URL URL_REG
0  http://www.example.it/remoteconnexion.aspx?u=x...   xx123

更新:

我只需要“ 123”部分而不是“ xx123”,其中“ xx”是十六进制数字

In [53]: df['URL_REG'] = df.URL.str.extract(r'direction=vente.aspx\%3pid\%\w{2}(\d+)\%*', 
                                            expand=False)

In [54]: df
Out[54]:
                                                 URL URL_REG
0  http://www.example.it/remoteconnexion.aspx?u=x...     123

您可以使用以下模式:

import re

url='http://www.example.it/remoteconnexion.aspxu=xxxxx@abc.it&direction=vente.aspx%3pid%xx123%63abcd'
output = re.findall('3pid%(.*?)%', url)

print(output)

输出:

['xx123']

然后将相同的模式应用于您的DataFrame。

例如:

import pandas as pd
import re

df = pd.DataFrame(['http://www.example.it/remoteconnexion.aspx?u=xxxxx@abc.it&direction=vente.aspx%3pid%xx123%63abcd'], columns = ['URL'])

output = df['URL'].apply(lambda x : re.findall('3pid%(.*?)%', x))

print(output)

# Or, maybe if you want to return the url and the data captured:
# output = df['URL'].apply(lambda x : (x, re.findall('3pid%(.*?)%', x)))
# output[0]
# >>> ('http://www.example.it/remoteconnexion.aspx?u=xxxxx@abc.it&direction=vente.aspx%3pid%xx123%63abcd', 
#   ['xx123'])

输出:

0    [xx123]
Name: URL, dtype: object

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM