繁体   English   中英

正则表达式中的变量?

[英]Variable inside a regular expression?

这是我的代码:

import urllib.request
import urllib.parse
import re

name=['hello','hi','ok']
text='"hello Paul" "are you there" "hi Jessie" "ok thank you"'
result=[]
for i in name:
    result.append(re.findall(r'"'+str(name)+'.*?"',str(text)))

我想得到

[['"hello Paul"'], ['"hi Jessie"'], ['"ok thank you"']]

但我明白了

[['"hello Paul"', '" "', '" "'], ['"hello Paul"', '" "', '" "'], ['"hello Paul"', '" "', '" "']]

如何修复我的代码以产生上述所需的结果?

首先考虑更改输入的格式。 话虽这么说,您可以使用所谓的环视,然后拆分这个:

import re
names = ['hello','hi','ok']
texts = '"hello Paul" "are you there" "hi Jessie" "ok thank you"'

rx = re.compile('(?<=") (?=")')
result = [text for text in rx.split(texts) for name in names if text.strip('"').startswith(name)]
print(result)

哪个生产

['"hello Paul"', '"hi Jessie"', '"ok thank you"']

请参阅ideone.com 上的演示

代码

import re
    
name=['hello','hi','ok']
text='"hello Paul" "are you there" "hi Jessie" "ok thank you"'
result= re.findall('("[^"]*(?:' + "|".join(name) + ')[^"]*")',str(text))

output

['"hello Paul"', '"hi Jessie"', '"ok thank you"']

解释

如果字符串包含在'"'之间,则"... "匹配

[^"]*匹配除'"'之外的所有字符,因此 ' '"' ' 中的每个字符都是封闭字符串

(?:' + "|".join(name) + ')匹配您给出的键之一, "|" 表示or?:表示该组是非捕获组

(...)是一个捕获灌浆,它捕获包含在'"'中并包含其中一个键的字符串中的所有内容

在线演示

在 Pythex 上使用预先编译好的密钥

暂无
暂无

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

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