簡體   English   中英

如何匹配一行中具有文件擴展名的任何字符串,並在python中僅打印匹配的單詞

[英]How To match Any string with file extension in a line and print only the matching word in python

我想搜索並匹配任何單詞,后跟一行擴展名.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擴展名yo it's a helo how are helloo.log.gz ,但是我想要的輸出只是helloo.log.gz 誰能在我用來打印出帶有擴展名的匹配單詞的reg exp上糾正我!

萬分感謝 !

.*更改為\\S* ,使其與空格不匹配。

ine_se = re.search(r"\S*\.log\.gz", line)

您實際上不需要正則表達式。 內置的字符串方法就足夠了。 例如,

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'
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM