正規表現: 記号 + - = で区切られたすべての単語を検索 (検索と置換)

正規表現: 記号 + - = で区切られたすべての単語を検索 (検索と置換)

次のようなシナリオがあります:

data-cycle-center-horz=true other words

data-cycle-caption=".custom-captions" other words

data-cycle-caption-template="{{slideNum}} other words

before words .data-cycle-caption-template="{{slideNum}} other words

.data-cycle-caption-template="{{slideNum}} other words

だから記号で区切られたすべての単語を見つける必要がある- = . "{

NOTEPAD++ 用の正規表現を作成して、他の単語なしで前後に記号がある単語 (文字列全体) を検索して削除しましたが、あまり良くありません。

検索: (?!\w+[-."={])

置換: (空白のまま)

期待される結果は次のようになります。

other words

other words

other words

before words other words

other words

答え1

  • Ctrl+H
  • 検索対象:(?:^|[+=."{}-]+)(?:\w+[+=."{}-]+)+\h*
  • と置換する:LEAVE EMPTY
  • チェック ラップアラウンド
  • 正規表現をチェック
  • Replace all

説明:

(?:             # start non capture group
  ^             # beginning of line
 |              # OR
  [+=."{}-]+    # 1 or more + = . " { } -
)               # end group
(?:             # start non capture group
  \w+           # 1 or more word character
  [+=."{}-]+    # 1 or more + = . " { } -
)+              # end group, may appear 1 or more times
\h*             # 0 or more horizontal spaces

画面キャプチャ:

ここに画像の説明を入力してください

答え2

これはPythonで書かれており、同じディレクトリのファイル「data.txt」からテストデータを読み込みます。

Pythonをインストールする

import os, re

path = "./data.txt"
if os.path.isfile(path): #use local leader file
    oFile = open(path)
    strFile = oFile.read() #get old leaders
    oFile.close()
else:
    print("File Not Found")

def replace(line):
    for i in line:
        if ( i == '-' or i == '=' or i == '.' or i == '"' or i == '{' or i == '}'):
            line = line.replace(i,"\n")#Delete \n and replace it with xyz to see
    return line

lines = strFile.split("\n")
for line in lines:

    answer = replace(line)

    print(answer)

データ サイクル センター horz 真のデータ サイクル キャプション カスタム キャプション データ サイクル キャプション テンプレート slideNum

答え3

あなたの質問から私が読み取ったのは、基本的にすべての単語を一致させたいが、区切りの特殊文字は一致させたくないということでしょうか?

[^-=."{}\r\n]+- = . "{これでうまくいくはずです。特殊文字や改行以外のすべてに一致します。

次のようなオンラインツールを使って正規表現を構築しテストすることができます。正規表現101

アップデート
次の正規表現は、説明したとおりに単語と末尾の空白を削除します。([^\s]+[-=."{}\r\n][^\s]+\s*)+

あなたの例でそれを正常にテストしました:

前に:

data-cycle-center-horz=true other words

data-cycle-caption=".custom-captions"  other words

data-cycle-caption-template="{{slideNum}}  other words

before words .data-cycle-caption-template="{{slideNum}}  other words

.data-cycle-caption-template="{{slideNum}}  other words

後:

other words

other words

other words

before words other words

other words

関連情報