开发者

Emacs: how to replace a string using a regular expression?

开发者 https://www.devze.com 2022-12-15 06:08 出处:网络
suppose i have the following in a text file (or dired buffer) open in emacs: file_01.txt file_02.txt ...

suppose i have the following in a text file (or dired buffer) open in emacs: file_01.txt file_02.txt ... file_99.txt

I开发者_如何学C want to query-replace or replace the files to 01_file.txt, etc.

I want to use query-replace-regexp or replace-regexp, but don't know what to put in. The search part i put in "file_..", but the ".." are read as periods in the replacement string. I'm beginning to learn regexp and don't know how to do this. Please help, thanks.


M-x replace-regexp invokes the function to replace with regular expressions.

For Replace regexp enter: \(file\)_\([0-9]+\)

This will create two groups, one that matches the 'file' part, and one that matches the number. The braces \( ... \) are necessary to make the match available later in the replacement string.

For Replace with enter: \2_\1

This inserts the second match from the search string (the numeric part), adds the _ (underscore) and then adds the first match from the search string (the 'file').

For more information on Emacs' regular expressions, see Regexp Syntax and Regexp Replace.

Once you have mastered the regexp basics you might want to check out the Emacs ReBuilder tool with M-x re-builder, which lets you build regexes interactively.

0

精彩评论

暂无评论...
验证码 换一张
取 消