camelWordsの単語を置き換える正規表現

camelWordsの単語を置き換える正規表現

CamelWordsの言葉を変えたいです。たとえば、テキストの「foo」を「bar」に置き換えます。

ifootest // not replace this foo
Ifootest // not replace this foo
IfooTest // << replace this foo
I foo Test // << replace this foo
I_foo_Test // << replace this foo

または、テキストで「Foo」を「Bar」に置き換えます。

IFootest // not replace
IFooTest // not replace
iFooTest // replace
i Foo Test //replace
I_Foo_Test // replace

ルールは私が単語を入力することです。

単語の最初の文字の前にある文字は、単語の最初の文字と大文字と小文字が同じではありません。

単語の最後の文字の後に続く文字は、単語の最後の文字と大文字と小文字が同じであってはなりません。

ベストアンサー1

次のことができます。

perl -pe 's/(?<![[:lower:]])foo(?![[:lower:]])/bar/g'

fooつまり、前後に小文字のないインスタンスを置き換えるには、負の反転演算とプレビュー演算子を使用します。

これはASCIIテキストでのみ機能します。ロケールの文字セットを使用してオプションを追加できます-Mopen=locale。または-CUTF-8テキストを処理するためのものです。

これは、最初または最後の文字が大文字であるFoo//などのfoO単語に対して調整する必要があります。FoO

すべての単語に対して機能させるには、次のようにします。

WORD=FoO REPL=bar perl  -pe 's{
  (?(?=[[:lower:]])      # if following character is lowercase
      (?<![[:lower:]])|  # preceding must not be lower 
      (?<![[:upper:]])   # otherwise preceding must not be upper
  ) \Q$ENV{WORD}\E
  (?(?<=[[:lower:]])     # if preceding character is lowercase
      (?![[:lower:]])|   # following must not be lower 
      (?![[:upper:]])    # otherwise following must not be upper
  )}{$ENV{REPL}}gx'

おすすめ記事