3

Python のルックアラウンドに関して問題があります。

>>> spacereplace = re.compile(b'(?<!\band)(?<!\bor)\s(?!or\b)(?!and\b)', re.I)
>>> q = "a b (c or d)"    
>>> q = spacereplace.sub(" and ", q)
>>> q
# What is meant to happen:
'a and b and (c or d)'

# What instead happens
'a and b and (c and or and d)'

正規表現は、「and」または「or」という単語の隣にないスペースに一致するはずですが、これは機能していないようです。

誰でもこれで私を助けることができますか?

編集:コメント者に応えて、正規表現を複数の行に分割しました。

(?<!\band) # Looks behind the \s, matching if there isn't a word break, followed by "and", there.
(?<!\bor)  # Looks behind the \s, matching if there isn't a word break, followed by "or", there.
\s         # Matches a single whitespace character.
(?!or\b)   # Looks after the \s, matching if there isn't the word "or", followed by a word break there.
(?!and\b)  # Looks after the \s, matching if there isn't the word "and", followed by a word break there.
4

1 に答える 1

2

生の文字列修飾子rをと混同したと思われbます。

>>> import re
>>> spacereplace = re.compile(r'(?<!\band)(?<!\bor)\s(?!or\b)(?!and\b)', re.I)
>>> q = "a b (c or d)"
>>> spacereplace.sub(" and ", q)
'a and b and (c or d)' 

場合によっては、正規表現が機能しない場合、フラグをDEBUG使用すると役立つ場合があります。re.DEBUGこの場合、単語の境界\bが検出されないことに気付くかもしれません。これにより、どこで間違いを探すべきかのヒントが得られる可能性があります。

>>> spacereplace = re.compile(b'(?<!\band)(?<!\bor)\s(?!or\b)(?!and\b)', re.I | re.DEBUG)
assert_not -1
  literal 8
  literal 97
  literal 110
  literal 100
assert_not -1
  literal 8
  literal 111
  literal 114
in
  category category_space
assert_not 1
  literal 111
  literal 114
  literal 8
assert_not 1
  literal 97
  literal 110
  literal 100
  literal 8


>>> spacereplace = re.compile(r'(?<!\band)(?<!\bor)\s(?!or\b)(?!and\b)', re.I | re.DEBUG)
assert_not -1
  at at_boundary
  literal 97
  literal 110
  literal 100
assert_not -1
  at at_boundary
  literal 111
  literal 114
in
  category category_space
assert_not 1
  literal 111
  literal 114
  at at_boundary
assert_not 1
  literal 97
  literal 110
  literal 100
  at at_boundary
于 2013-05-04T11:21:13.823 に答える