我试图在URL字符串上使用python正则表达式.
id= 'edu.vt.lib.scholar:http/ejournals/VALib/v48_n4/newsome.html'
>>> re.search('news|ejournals|theses',id).group()
'ejournals'
>>> re.findall('news|ejournals|theses',id)
['ejournals', 'news']
Run Code Online (Sandbox Code Playgroud)
根据http://docs.python.org/2/library/re.html#finding-all-adverbs上的文档,它说search()匹配第一个,并查找字符串中所有可能的匹配.
我想知道为什么'新闻'没有被搜索捕获,即使它在模式中被宣布为第一.
我使用了错误的模式吗?我想搜索字符串中是否出现任何关键字.
你正在向后思考。正则表达式遍历目标字符串寻找"news"OR "ejournals"OR"theses"并返回它找到的第一个。在这种情况下,"ejournals"首先出现在目标字符串中。