簡體   English   中英

表達到評論或行尾

[英]Expression up to comment or end of line

雖然這個問題類似於這個主題

我想在使用正則表達式構造代碼時可能會出錯。

我希望將一行中的任何內容與注釋(“#”)或行尾(如果它沒有注釋)匹配。

我正在使用的正則表達式是: (.*)(#|$)

(.*) =一切
(#|$) =評論或行尾

編碼:

OPTION = re.compile(r'(?P<value>.*)(#|$)')
file = open('file.txt')
lines = file.read()
for line in lines.split('\n'):
    get_match = OPTION.match(line)
    if get_match:
        line_value = get_match.group('value')
        print "Match=  %s" % line_value

以上工作但不刪除評論。 如果文件有一行如下:

this is a line   # and this is a comment

運行代碼時我仍然得到整行。

我是否在正則表達式中缺少其他值/信息,或者我是否需要對代碼進行更改?

*是貪婪的(消耗盡可能多的字符串),因此消耗整行(超過#和到行尾)。 改成 ”。*?” 它會起作用。

有關更多信息,請參閱正則表達式HOWTO

這是正確的正則表達式做這樣的事情:

([^#]*)(#.*)?

另外,你為什么不用它

file = open('file.txt')
for line in file:

@Can,@Benji和@ΤΖΩΤΖΙΟΥ舉三個優秀的解決方案,它是時間的他們,看看他們如何快速匹配(這是什么好玩的timeit是-樂趣無意義微基准測試;-)。 例如:

$ python -mtimeit -s'import re; r=re.compile(r"([^#]*)(#.*)?"); s="this is a line   # and this is a comment"' 'm=r.match(s); g=m.group(1)'
100000 loops, best of 3: 2.02 usec per loop

VS

$ python -mtimeit -s'import re; r=re.compile(r"^(.*?)(?:#|$)"); s="this is a line   # and this is a comment"' 'm=r.match(s); g=m.group(1)'
100000 loops, best of 3: 4.19 usec per loop

VS

$ python -mtimeit -s'import re; r=re.compile(r"(.*?)(#|$)"); s="this is a line   # and this is a comment"' 'm=r.match(s); g=m.group(1)'
100000 loops, best of 3: 4.37 usec per loop

獲勝者是......混合的模式! - )

$ python -mtimeit -s'import re; r=re.compile(r"(.*?)(#.*)?"); s="this is a line   # and this is a comment"' 'm=r.match(s); g=m.group(1)'
1000000 loops, best of 3: 1.73 usec per loop

免責聲明:當然,如果這是一個真正的基准測試練習,速度確實很重要,人們會嘗試s許多不同和相關的值,超出這樣的微基准測試等等的測試。但是,我仍然發現timeit是取之不盡的源泉有趣的 - - !)

使用此正則表達式:

^(.*?)(?:#|$)

與非貪婪改性劑( ? ),則.*表達將盡快達到任一散列標志或結束線匹配。 默認是盡可能地匹配,這就是為什么你總是拿到了整條生產線。

暫無
暫無

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

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