情報科学屋さんを目指す人のメモ

方法・手順・解説を書き残すブログ。私と同じことを繰り返さずに済むように。

Sublime Text:文字列を連続で正規表現置換するマクロを組む方法

Sublime Text (5)

Sublime Text 3 で文字列の置換を連続実行するマクロを組んだので、その方法を紹介します。

RegReplaceのインストール

「Preference>Package Control」を開いて、「Package Control: Install Package」を実行します。

そして、「RegReplace」をインストールします。

「置換」の内容を定義する

次に、「Preference>Package Settings>Reg Replace>Setting - Users」を開きます。

ここに、「置換」の内容を登録します(ちょっと変な例だけれど)。

ここでは、「replace_1」という置換と、「replace_2」という置換の、2つを登録しています。

正規表現で指定した「find」を、「replace」で指定した文字列に置換します。

{
	"replacements": {
		"replace_1": { "find": "\n", "replace": "<br />\n" },
		"replace_2": { "find": "・(.+)$", "replace": "<li>\\1</li>" }
	}
}

コマンドを定義する

次に、「Preference>Package Settings>Reg Replace>Commands - Users」を開きます。

そして、以下のように「RegReplace: replace1and2」という名前のコマンドを定義しました。

ここでは、その名前のコマンドを実行すると、「replace_1」と「replace_2」が実行されるようにしました。

[
	{
		"caption": "RegReplace: replace1and2",
		"command": "reg_replace",
		"args": {
			"replacements": [
				"replace_1",
				"replace_2"
			]
		}
	}
]

使い方(コマンドの実行方法)

「Tools>Command Palette」を開くと、コマンド入力欄が表示されるので、そこに、「caption」で指定したコマンド名を入力し、Enterキーで実行します。

sublime-text-3-reg-replace-package-command-palette

入力補完がされるので、一部入力でも出てきます。

実行すると、現在表示しているタブのファイルに、全置換が順番に適用されていきます。

注意点

注意ポイントは以下のとおり:

  • 括弧の種類「{}」「[]」を間違えないように
  • 「\1」は、「\\1」としないと保存時にエラー(Error trying to parse settings: Invalid escape in Packages\User\reg_replace.sublime-settings)
  • コマンド名は、「caption」で指定した文字列になるので、「captionはただの説明書きだろ」と勘違いして省略したりしない。「command」に指定する文字列は、設定内部での参照用であって、コマンド名としてcommand paletteに出てくることはない。

記述の際の参考資料

今回は、最も簡単なケースを例示したので、その他の用法、記述方法については、以下を参考にしてください。

置換設定サンプル

////////////////////////////////
// Regex with scope qualifiers//
////////////////////////////////
// Required parameters:
//     find:    Regex description of what you would like to target.
//
// Optional parameters:
//     replace:      description of what you would like to replace target with.
//                   Variables are okay for non-literal searches and are done by escaping
//                   the selection number \\1 etc.  Default value is "\\0".
//     literal:      Boolean setting to define whether the find and replace is literal or not.
//                   Default is false.
//     greedy:       Boolean setting to define whether search is greedy or not. Default is true.
//     case:         Boolean defining case sensitivity.  True equals sensitive. Defualt is true.
//     dotall:       Boolean defining whether to use dotall flag in regex (include \n etc. when using dot).
//                   Default is False
//     scope_filter: an array of scope qualifiers for the match.
//                       - Any instance of scope qualifies match: scope.name
//                       - Entire match of scope qualifies match: !scope.name
//                       - Any instance of scope disqualifies match: -scope.name
//                       - Entire match of scope disqualifies match: -!scope.name

//////////////////////////////////////////////////////////////
// Scope search with regex qualifier (also find and replace)//
//////////////////////////////////////////////////////////////
// Required parameters:
//     scope:    scope you would like to target
//
// Optional parameters:
//     find:            regex description that is to be applied to the scope
//                      to qualify.  Also can be used to find and replace
//                      within the found scope.  Default is None.
//     replace:         description of what you would like to replace within the scope.
//                      Default value is "\\0".
//     literal:         Boolean setting to define whether the find and replace is literal or not.
//                      Default is false.
//     greedy_replace:  Boolean setting to define whether regex search is greedy or not. Default is true.
//     greedy_scope:    Boolean setting to define whether scope search is greedy or not. Default is true.
//     case:            Boolean setting to define whether regex search is case sensitive. Default is true.
//     dotall:          Boolean defining whether to use dotall flag in regex (include \n etc. when using dot).
//                      Default is False
//     multi_pass_regex:Boolean setting to define whether there will be multiple sweeps on the scope region
//                      region to find and replace all instances of the regex, when regex cannot be formatted
//                      to find all instances in a greedy fashion.  Default is false.
{
    // Use sub notify if available
    "use_sub_notify": true,

    "replacements": {
        // Example replacements
        "html5_remove_deprecated_type_attr": {
            "find": "(<(style|script)[^>]*)\\stype=(\"|')text/(css|javascript)(\"|')([^>]*>)",
            "replace": "\\1\\6",
            "greedy": true,
            "case": false
        },
        // remove_json_dangling_commas
        "remove_json_dangling_commas": {
            "find": ",([\\r\\n\\s]*)(\\]|\\})",
            "replace": "\\1\\2",
            "greedy": true,
            "scope_filter": ["-string", "-comment"]
        },
        "remove_html_comments": {
            "find": "<!--[\\s\\S]+?-->",
            "replace": "",
            "scope_filter": ["!comment"],
            "greedy": true,
            "case": true
        },
        "remove_trailing_spaces": {
            "find": "[ \\t]+$",
            "replace": "",
            "greedy": true,
            "case": true
        },
        // Delete a comment or comment blocks
        "remove_comments": {
            "scope": "comment",
            "find" : "([^\\n\\r]+)",
            "replace": "",
            "greedy_replace": true
        }
    },

    // If on_save is true, RegReplace will search through the file patterns listed below right before a file is saved,
    // if the file name matches a file pattern, the sequence will be applied before the file is saved.
    // RegReplace will apply all sequences that apply to a given file in the order they appear below.
    "on_save": false,

    // Highlight visual settings
    "on_save_highlight_scope": "invalid",
    "on_save_highlight_style": "outline",

    // on_save replacements
    "on_save_sequences": [
        // An example on_save event that removes dangling commas from json files
        // - file_regex: an array of regex strings that must match the file for the sequence to be applied
        // - case: regex case sensitivity (true|false) false is default (this setting is optional)
        // - file_pattern: an array of file patterns that must match for the sequence to be applied
        // - sequence: an array of replacement definitions to be applied on saving the file
        // - multi_pass: perform multiple passes on file to catch all regex instances
        // - action: (mark|fold|unfold) instead of replace.  Only one action can be used
        {
            "file_regex": [".*\\.sublime-(settings|commands|menu|keymap|mousemap|theme|build|project|completions|commands)"],
            "file_pattern": ["*.json"],
            "sequence": ["remove_json_dangling_commas"]
        },
        // An example on_save_sequence that targets all files and trims trailing spaces
        // - file_pattern: an array of file patterns that must match for the sequence to be applied
        // - sequence: an array of replacement definitions to be applied on saving the file
        {"file_pattern": ["*"], "sequence": ["remove_trailing_spaces"]}
    ],

    // Show replace results in panel
    "results_in_panel": false,

    // Maximum sweep threshold for multi-pass
    "multi_pass_max_sweeps": 100,

    // Color? (scope)
    "find_highlight_color": "invalid",

    // Highlight style? (outline|solid|underline)
    "find_highlight_style": "outline",

    // Search under selection(s) if and only if exists
    "selection_only": false,

    // Use extended backreferences
    "extended_back_references": false
}

コマンド設定サンプル

[
    // Clear all find highlights
    {
        "caption": "Reg Replace: Clear Highlights",
        "command": "reg_replace",
        "args": {"clear": true}
    },

    // Example commands.
    // {
    //     "caption": "Reg Replace: HTML5 Remove Deprecated Type Attr",
    //     "command": "reg_replace",
    //     "args": {"replacements": ["html5_remove_deprecated_type_attr"]}
    // },
    // {
    //     "caption": "Reg Replace: Remove Trailing Spaces",
    //     "command": "reg_replace",
    //     "args": {"replacements": ["remove_trailing_spaces"]}
    // },
    // // Chained replacements in one command
    // {
    //     "caption": "Reg Replace: Remove HTML Comments and Trailing Spaces",
    //     "command": "reg_replace",
    //     "args": {"replacements": ["remove_html_comments", "remove_trailing_spaces"]}
    // },

    // Preferences
    {
        "caption": "Preferences: Reg Replace Settings – Default",
        "command": "open_file",
        "args": { "file": "${packages}/RegReplace/reg_replace.sublime-settings" }
    },
    {
        "caption": "Preferences: Reg Replace Settings – User",
        "command": "open_file",
        "args": { "file": "${packages}/User/reg_replace.sublime-settings" }
    },
    {
        "caption": "Preferences: Reg Replace Commands – Default",
        "command": "open_file",
        "args": { "file": "${packages}/RegReplace/Default.sublime-commands" }
    },
    {
        "caption": "Preferences: Reg Replace Commands – User",
        "command": "open_file",
        "args": { "file": "${packages}/User/Default.sublime-commands" }
    }
]

RegReplace公式ページ

RegReplaceの公式ドキュメントはこちら:RegReplace Documentation

コメント(0)

新しいコメントを投稿