我想在一行中搜索并匹配任何单词后跟文件扩展名.log.gz,并仅打印匹配的单词。
以下是我尝试过的代码示例
# Global Import Variables
import Tkinter, Tkconstants, tkFileDialog
line = "helo how are helloo.log.gz you"
line_se = re.search(r"\b.*\.log.gz", line)
if line_se:
print line_se
print("yo it's a {}".format(line_se.group(0)))
但输出是整行,直到扩展为止
yo it's a helo how are helloo.log.gz
,但我想要的输出只是helloo.log.gz
。任何人都可以在reg exp上纠正我,我用它来打印出带扩展名的匹配单词!
非常感谢!
答案 0 :(得分:1)
将.*
更改为\S*
,使其与空格不匹配。
ine_se = re.search(r"\S*\.log\.gz", line)
答案 1 :(得分:0)
你实际上不需要正则表达式。内置的字符串方法就足够了。例如,
from functools import partial
def find_filename(text, extension):
"""Finds the first word in 'text' that ends with 'extension.',
or 'None' if 'text' doesn't contain such a word."""
words = text.split()
for word in words:
if word.endswith('.' + extension):
return word
find_log_gz = partial(find_filename, extension="log.gz")
# Test:
>>> find_log_gz("helo how are helloo.log.gz you")
'helloo.log.gz'
>>>