1

検閲された冒とく的な表現の使用を検出する軽量ツールを構築する際に、単語境界の末尾にある特殊文字を検出するのが非常に難しいことに気付きました。

文字列のタプルを使用して、OR された単語境界の正規表現を作成します。

import re

PHRASES = (
    'sh\\*t',  # easy
    'sh\\*\\*',  # difficult
    'f\\*\\*k',  # easy
    'f\\*\\*\\*',  # difficult
)

MATCHER = re.compile(
    r"\b(%s)\b" % "|".join(PHRASES), 
    flags=re.IGNORECASE | re.UNICODE)

問題は、*が単語境界の隣で検出できるものではないことです\b

print(MATCHER.search('Well f*** you!'))  # Fail - Does not find f***
print(MATCHER.search('Well f***!'))  # Fail - Does not find f***
print(MATCHER.search('f***'))  # Fail - Does not find f***
print(MATCHER.search('f*** this!'))  # Fail - Does not find f***
print(MATCHER.search('secret code is 123f***'))  # Pass - Should not match
print(MATCHER.search('f**k this!'))  # Pass - Should find 

特殊文字で終わるフレーズをサポートする便利な方法でこれを設定するためのアイデアはありますか?

4

4 に答える 4