正規表現でPythonスクリプト内のすべての文字列をキャプチャ

iperetta:

:この質問はこの答えに適応しようとした後、私の失敗に触発された正規表現:引用符の間の値をつかむを

次のPythonスクリプトを考えてみましょう(t.py):

print("This is also an NL test")
variable = "!\n"
print('And this has an escaped quote "don\'t"  in it ', variable,
      "This has a single quote ' but doesn\'t end the quote as it" + \
      " started with double quotes")
if "Foo Bar" != '''Another Value''':
    """
    This is just nonsense
    """
    aux = '?'
    print("Did I \"failed\"?", f"{aux}")

私は、キャプチャするすべての文字列を通り、その中:

  • This is also an NL test
  • !\n
  • And this has an escaped quote "don\'t" in it
  • This has a single quote ' but doesn\'t end the quote as it
  • started with double quotes
  • Foo Bar
  • Another Value
  • This is just nonsense
  • ?
  • Did I \"failed\"?
  • {aux}

私が使用して別のPythonスクリプトを書いたre正規表現に私の試みから、モジュールをして、それらのほとんど見つかったものです。

import re
pattern = re.compile(r"""(?<=(["']\b))(?:(?=(\\?))\2.)*?(?=\1)""")
with open('t.py', 'r') as f:
    msg = f.read()
x = pattern.finditer(msg, re.DOTALL)
for i, s in enumerate(x):
    print(f'[{i}]',s.group(0))

以下の結果:

  • [0] And this has an escaped quote "don\'t" in it
  • [1] This has a single quote ' but doesn\'t end the quote as it started with double quotes
  • [2] Foo Bar
  • [3] Another Value
  • [4] Did I \"failed\"?

私の障害を改善するために、私はまた、完全に私が見つけことができるものを複製することができませんでしたregex101.com

ここでは、画像の説明を入力します。

私は道でのPython 3.6.9を、使用しています、と私はこの1つをクラックするために正規表現に多くの洞察を求めています。

CertainPerformance:

照合するため'''か、"""または'または"区切り文字として、最初のグループにそのすべてを置きます:

('''|"""|["'])

入れないでください\bこれらの文字列は、単語文字以外の何かを始めるとき、それは文字列が一致しませんので、それは後に。

あなたはことを確認するので、最終的なエンジンは、次の反復を開始したときに区切り文字が開始区切り文字として扱われていない、あなたは完全に(ちょうどそれを先読みしない)それを一致させる必要があります。

中央部には、何も一致するが、区切り文字は指定できます。

((?:\\.|.)*?)

すべて一緒にそれを置きます:

('''|"""|["'])((?:\\.|.)*?)\1

そして、あなたが望む結果は、第二のキャプチャグループになります。

pattern = re.compile(r"""(?s)('''|\"""|["'])((?:\\.|.)*?)\1""")
with open('t.py', 'r') as f:
    msg = f.read()
x = pattern.finditer(msg)
for i, s in enumerate(x):
    print(f'[{i}]',s.group(2))

https://regex101.com/r/dvw0Bc/1

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=23965&siteId=1