0

Text

How are you?
I'm just fine.

I need to add some suffix to the next words: are and fine.

I try this:

\(are\)|\(fine\)

but it doesn't help.

enter image description here

  • No code. I need this for replace-regexp command. I updated my post – Alexei Jun 14 at 15:21
  • 3
    I think you're after C-M-% are\|fine RET \&-test RET ! – Basil Jun 14 at 15:46
  • 2
    @Basil Please convert your comment into an answer and maybe stress that the or operator in Emacs regexps is \| and not the Perl version |. – Tobias Jun 14 at 15:57
  • @Tobias Done, thanks. – Basil Jun 14 at 16:51
3

I try this:

\(are\)|\(fine\)

This is valid Elisp regexp syntax, but it's probably not what you were after. In particular, alternations are delimited by \| in Elisp syntax, not | as in POSIX ERE and Perl syntax. In Elisp regexps, | is a literal vertical bar character. See (emacs) Regexp Backslash.

In addition, the grouping constructs \(...\) are unnecessary in this case (though they don't do any harm), since you are subsequently referring to the whole match \&, not the first or second group \1 or \2, respectively. See (emacs) Regexp Replace.

So what you are probably after is C-M-%are\|fineRET\&-testRET!.

1

The question has been kind of answered, but, I am going to focus on the "add a suffix" part. Here we go:

run the command: M-x query-replace

which for vanilla emacs is normally mapped to: C-M-%

you will be prompted with: Query replace regexp: and type in: \(are\|fine\)

and hit return

next, you will be prompted: Query replace regexp \(are|fine\) with: and you type: \1 boop the snoot

and hit return

you will be prompted (y or n) on each match if you want to do the replacement.

with this, you will convert:

How are you?
I'm just fine.

to:

How are boop the snoot you?
I'm just fine boop the snoot.

so what just happened?

the brackets () in the matcher are telling the regex system to store that part of the match (in you case, are or fine). In the replacer, we are telling emacs to replace the matched text with the first matched text (\1) and a new suffix boop the snoot.

You can also have multiple match groups: \([a-z]+\) \([0-9]+\) \(A-Z]\)

and reference them in a replacer: \3 \1 \2

which would rearrange this: boop 8 SNOOTS

to: SNOOTS boop 8

the slashes \ are escape characters that are sometimes required to alter the meaning of a character (take me literally).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.