我想要做什么:解析查询以查找前导或尾随?这将导致对字符串的其余部分进行搜索。
“foobar?”或“?foobar”导致搜索。 “foobar”会导致一些其他行为。
此代码在解释器中按预期工作:
>>> import re
>>> print re.match(".+\?\s*$","foobar?")
<_sre.SRE_Match object at 0xb77c4d40>
>>> print re.match(".+\?\s*$","foobar")
None
来自 Django 应用程序的这段代码不会:
doSearch = { "text":"Search for: ", "url":"http://www.google.com/#&q=QUERY", "words":["^\?\s*",".+\?\s*$"] }
...
subQ = myCore.lookForPrefix(someQuery, doSearch["words"])
...
def lookForPrefix(query,listOfPrefixes):
for l in listOfPrefixes:
if re.match(l, query):
return re.sub(l,'', query)
return False
Django 代码永远不会匹配尾随的“?”,所有其他正则表达式都可以正常工作。
以及为什么不这样做的想法?
最佳答案
问题出在你的第二个正则表达式中。它匹配整个查询,因此使用 re.sub()
将其全部替换为空字符串。 IE。 lookForPrefix('foobar?',listOfPrefixes)
将返回''
。您可能正在检查 if
中的返回值,因此它将空字符串评估为 false。
要解决这个问题,您只需将第二个正则表达式更改为 \?\s*$
并使用re.search()
而不是re.match()
,因为后者要求您的正则表达式从字符串的开头匹配。
doSearch = { "text":"Search for: ", "url":"http://www.google.com/#&q=QUERY", "words":["^\?\s*","\?\s*$"] }
def lookForPrefix(query,listOfPrefixes):
for l in listOfPrefixes:
if re.search(l, query):
return re.sub(l,'', query)
return False
结果:
>>> lookForPrefix('?foobar', doSearch["words"])
'foobar'
>>> lookForPrefix('foobar?', doSearch["words"])
'foobar'
>>> lookForPrefix('foobar', doSearch["words"])
False
编辑:事实上,您不妨将两个正则表达式合并为一个:^\?\s*|\?\s*$
。这将同样有效。
关于Python正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2206026/