Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 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.

like image 718
Vinh Nguyen Avatar asked Jan 05 '10 02:01

Vinh Nguyen


People also ask

How do I replace a string in Emacs?

When you want to replace every instance of a given string, you can use a simple command that tells Emacs to do just that. Type ESC x replace-string RETURN, then type the search string and press RETURN. Now type the replacement string and press RETURN again.

Can you use regex to replace string?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match in if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

How does regex replace work?

The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string. standardizes spacing in character data by replacing one or more spaces between text characters with a single space.


1 Answers

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.

like image 107
cschol Avatar answered Sep 25 '22 08:09

cschol