1

次の入力を一致させたい。複数行の文字列を使用せずにグループを特定の回数一致させるにはどうすればよいですか? (^(\d+) (.+)$){3}) のようなもの (ただし、動作しません)。

sample_string = """Breakpoint 12 reached 
         90  good morning
     91  this is cool
     92  this is bananas
     """
pattern_for_continue = re.compile("""Breakpoint \s (\d+) \s reached \s (.+)$
                                 ^(\d+)\s+  (.+)\n
                                 ^(\d+)\s+  (.+)\n
                                 ^(\d+)\s+  (.+)\n
                                  """, re.M|re.VERBOSE)
matchobj = pattern_for_continue.match(sample_string)
    print matchobj.group(0)
4

2 に答える 2

3

式とサンプルには一連の問題があります。

  • VERBOSEを使用すると、すべてのスペースが一致しなくなるため、最初の行の数字の前後のスペースも無視されます。\sスペースをまたはに置き換えます[ ](後者はリテラルスペースにのみ一致し、前者は改行とタブにも一致します)。

  • 入力サンプルには、各行の数字の前に空白がありますが、サンプルパターンでは、数字が行の先頭にある必要があります。その空白を許可するか、サンプル入力を修正してください。

  • 最大の問題は、繰り返しグループ内のキャプチャグループ(つまり、最後(\d+)にある大きなグループ内{3})は最後の一致のみをキャプチャすることです。前の2つの一致した行ではなく、92とを取得します。this is bananas

それをすべて克服するには、3行に対してそのパターンを明示的に繰り返す必要があります。Pythonを使用して、その繰り返しを実装できます。

linepattern =  r'[ ]* (\d+) [ ]+ ([^\n]+)\n'

pattern_for_continue = re.compile(r"""
    Breakpoint [ ]+ (\d+) [ ]+ reached [ ]+ ([^\n]*?)\n
    {}
""".format(linepattern * 3), re.MULTILINE|re.VERBOSE)

これは、サンプル入力に対して、次を返します。

>>> pattern_for_continue.match(sample_string).groups()
('12', '', '90', 'hey this is a great line', '91', 'this is cool too', '92', 'this is bananas')

余分な3行の数字の前のスペースを本当に一致させたくない場合は、[ ]*から最初のパターンを削除できますlinepattern

于 2013-03-18T17:55:33.357 に答える
1

コード

次のようなものが必要です。

import re

sample_string = """Breakpoint 12 reached 
90  hey this is a great line
91  this is cool too
92  this is bananas
"""
pattern_for_continue = re.compile(r"""
    Breakpoint\s+(\d+)\s+reached\s+\n
    (\d+)  ([^\n]+?)\n
    (\d+)  ([^\n]+?)\n
    (\d+)  ([^\n]+?)\n
""", re.MULTILINE|re.VERBOSE)
matchobj = pattern_for_continue.match(sample_string)

for i in range(1, 8):
    print i, matchobj.group(i)
print "Entire match:"
print matchobj.group(0)

結果

1 12
2 90
3   hey this is a great line
4 91
5   this is cool too
6 92
7   this is bananas
Entire match:
0 Breakpoint 12 reached 
90  hey this is a great line
91  this is cool too
92  this is bananas

理由

  • re.VERBOSE は、正規表現に明示的な空白を必要とします。複数行の文字列でデータを左揃えにすることで、これを部分的に修正しました。おそらく実際のコードにはこれがないので、これは正当化されると思います。複数行の文字列を編集した結果の可能性があります。

  • に置き換える必要があり$ます\n

  • 貪欲でない一致が必要です

于 2013-03-18T17:43:28.890 に答える