用于提取信息的Python Regex循环



我试图使一个函数使一个应用函数,结束是找到数字后面跟着3个字符在这种情况下alc。预期结果应为= 54

import pandas as pd 
import regex as re 
numeros=[0,1,2,3,4,5,6,7,8,9]
i="sdASK23LJFASDFKJGHASDLKJF123HALSDKJFHASDF54 alcobas"

df=df.head(3)
def re_alcoba(i):
i=i.replace(" ", "")
patron_acoba=re.compile(r"alc")
matches=patron_acoba.finditer(i)
contador=1
numero_alcobas=[]
for match in matches:
index=match.start()
while contador < 3: 
numero=i[index-contador]
contador+=1
if numero in numeros: 
numero_alcobas.insert(0,numero)
respuesta="".join(numero_alcobas)
return respuesta


respuesta=re_alcoba(i)

My circle cannot work

如果你想在alc之前直接写数字那么你不需要所有这些代码,只需要(d+)alc

import regex as re 
i = "sdASKLJFASDFKJGHASDLKJFHALSDKJFHASDF54alcobas"
i = i.replace(" ", "")
results = re.findall("(d+)alc", i)
print(results) # ['54']
i = "4asd5alc"
i = i.replace(" ", "")
results = re.findall("(d+)alc", i)
print(results) # ['5']

由于示例字符串中有空格,您可以匹配除数字后面的换行符以外的可选空格:

(d+)[^Sn]*alc

Regex演示

import re
pattern = r"(d+)[^Sn]*alc"
s = ("sdASK23LJFASDFKJGHASDLKJF123HALSDKJFHASDF54 alcobasn"
"4asd5alc")

print(re.findall(pattern, s))

输出
['54', '5']

相关内容

  • 没有找到相关文章

最新更新