2

通常のテキストを囲む一重引用符を削除しようとしています。たとえば、次のリストがあるとします。

alist = ["'ABC'", '(-inf-0.5]', '(4800-20800]', "'\\'(4.5-inf)\\''", "'\\'(2.75-3.25]\\''"]

「'ABC'」を「ABC」に変えたいのですが、他の引用符はそのままにしておきます。

alist = ["ABC", '(-inf-0.5]', '(4800-20800]', "'\\'(4.5-inf)\\''", "'\\'(2.75-3.25]\\''"]

以下のようにlook-headを使用しようとしました:

fixRepeatedQuotes = lambda text: re.sub(r'(?<!\\\'?)\'(?!\\)', r'', text)
print [fixRepeatedQuotes(str) for str in alist]

エラーメッセージを受け取りました:

sre_constants.error: look-behind requires fixed-width pattern. 

他の回避策はありますか?よろしくお願いします!

4

2 に答える 2

1

試してみてください:

result = re.sub("""(?s)(?:')([^'"]+)(?:')""", r"\1", subject)

説明

"""
(?:         # Match the regular expression below
   '           # Match the character “'” literally (but the ? makes it a non-capturing group)
)
(           # Match the regular expression below and capture its match into backreference number 1
   [^'"]       # Match a single character NOT present in the list “'"” from this character class (aka any character matches except a single and double quote)
      +           # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
(?:         # Match the regular expression below
   '           # Match the character “'” literally (but the ? makes it a non-capturing group)
)
"""
于 2012-08-09T04:21:55.840 に答える
1

re.sub関数を置換テキストとして受け入れます。したがって、

re.sub(r"'([A-Za-z]+)'", lambda match: match.group(), "'ABC'")

収量

"ABC"
于 2012-08-09T04:25:57.833 に答える