【发布时间】:2013-04-07 12:27:22
【问题描述】:
我要做的是获取包含通配符的用户输入文本(所以我需要保持这种方式),但还要查找指定的输入。因此,例如,我在下面工作时使用管道 |。
我想出了如何做到这一点:
dual = 'a bunch of stuff and a bunch more stuff!'
reobj = re.compile('b(.*?)f|\s[a](.*?)u', re.IGNORECASE)
result = reobj.findall(dual)
for link in result:
print link[0] +' ' + link[1]
返回:
不知道
和一个b
还有
dual2 = 'a bunch of stuff and a bunch more stuff!'
#So I want to now send in the regex codes of my own.
userin1 = 'b(.*?)f'
userin2 = '\s[a](.*?)u'
reobj = re.compile(userin1, re.IGNORECASE)
result = reobj.findall(dual2)
for link in result:
print link[0] +' ' + link[1]
返回:
你 n
你 n
我不明白它在做什么,好像我摆脱了打印中的所有保存链接 [0] 我得到:
你
你
但是我可以传入用户输入的正则表达式字符串:
dual = 'a bunch of stuff and a bunch more stuff!'
userinput = 'b(.*?)f'
reobj = re.compile(userinput, re.IGNORECASE)
result = reobj.findall(dual)
print(result)
但是当我尝试使用管道将其更新为两个用户字符串时:
dual = 'a bunch of stuff and a bunch more stuff!'
userin1 = 'b(.*?)f'
userin2 = '\s[a](.*?)u'
reobj = re.compile(userin1|userin2, re.IGNORECASE)
result = reobj.findall(dual)
print(result)
我得到错误:
reobj = re.compile(userin1|userin2, re.IGNORECASE) 类型错误:| 不支持的操作数类型:“str”和“str”
如果我在 userin1|userin2 周围加上括号 () 或 [],我经常会收到此错误。
我发现了以下内容:
但无法让它工作;..{-( .
我想做的是能够理解如何传入这些正则表达式变量,例如 OR 的变量,并返回两者的所有匹配项以及 AND 之类的东西——这最终很有用将对文件进行操作,并让我知道哪些文件包含具有各种逻辑关系 OR、AND 等的特定单词。
非常感谢您的意见,
布赖恩
【问题讨论】:
-
您必须将管道用作字符串,而不是运算符。想想:“a|b”而不是“a”| “乙”