簡體   English   中英

是否有單個Python正則表達式可以將以“#”開頭的行上的所有“ foo”更改為“ bar”?

[英]Is there a single Python regex that can change all “foo” to “bar” on lines starting with “#”?

是否可以編寫一個可以應用於多行字符串的Python正則表達式,並將所有出現的“ foo”更改為“ bar”,但只能在以“#”開頭的行上進行編寫?

我能夠使用Perl的\\ G正則表達式sigil使其在Perl中工作,該正則表達式sigil與上一場比賽的結尾相匹配。 但是,Python似乎不支持此功能。

如果有幫助,這是Perl解決方案:

my $x =<<EOF;
# foo
foo
# foo foo
EOF

$x =~ s{
        (            # begin capture
          (?:\G|^\#) # last match or start of string plus hash
          .*?        # followed by anything, non-greedily
        )            # end capture
        foo
      }
      {$1bar}xmg;

print $x;

正確的輸出,當然是:

# bar
foo
# bar bar

可以用Python完成嗎?


編輯:是的,我知道可以將字符串分成幾行並測試每一行,然后決定是否應用轉換,但是請我相信在這種情況下這樣做並非易事。 我確實確實需要使用單個正則表達式來做到這一點。

lines = mystring.split('\n')
for line in lines:
    if line.startswith('#'):
        line = line.replace('foo', 'bar')

無需正則表達式。

使用正則表達式看起來很容易:

>>> import re
... text = """line 1
... line 2
... Barney Rubble Cutherbert Dribble and foo
... line 4
... # Flobalob, bing, bong, foo and brian
... line 6"""
>>> regexp = re.compile('^(#.+)foo', re.MULTILINE)
>>> print re.sub(regexp, '\g<1>bar', text)
line 1
line 2
Barney Rubble Cutherbert Dribble and foo
line 4
# Flobalob, bing, bong, bar and brian
line 6

但是,然后嘗試您的示例文本不是很好:

>>> text = """# foo
... foo
... # foo foo"""
>>> regexp = re.compile('^(#.+)foo', re.MULTILINE)
>>> print re.sub(regexp, '\g<1>bar', text)
# bar
foo
# foo bar

因此,請嘗試以下操作:

>>> regexp = re.compile('(^#|\g.+)foo', re.MULTILINE)
>>> print re.sub(regexp, '\g<1>bar', text)
# foo
foo
# foo foo

似乎可行,但是我在文檔中找不到\\ g!

道德:不要在喝了幾杯啤酒之后嘗試編碼。

\\ g和perl一樣在python中工作,並且在docs中

“除了如上所述的字符轉義和反向引用外,\\ g將使用與名稱組匹配的子字符串,名稱組的名稱由(?P ...)語法定義。\\ g使用​​相應的組號; \\ g <2因此>等效於\\ 2,但在諸如\\ g <2> 0之類的替換中並沒有歧義。\\ 20將被解釋為對組20的引用,而不是對組2的引用,后跟文字字符'0 '。后向引用\\ g <0>替換RE匹配的整個子字符串。”

暫無
暫無

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

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