0

I am using replace-regexp interactively. Can I programmatically refer to a match or otherwise interpolate values in the replacement string? In Ruby, for example, it is easily done, by using the #{ <code> } syntax.

For example: Lets say that I have a string which looks like "GClass::DhF". I want to remove the substring "::Dh", replace it with whitespace, and convert to a lowercase the first character that appears after "Dh". So, for example, "GClass::DhF" will be converetd to "GClass f", and "GClass::DhY" will be converted to "GClass y". The idea is that instead of inputting GClass \1, I input what in LISP would be (strcat "GClass " (lowercaseString \1)).

  • 1
    Please elaborate. Your question is not very clear, so far. Show what you've tried, and describe in more detail what you are aiming at. – Drew Nov 20 '17 at 16:21
  • O.K. Lets say that I have a string which looks like "GClass::DhF". I want to remove the "::Dh", replace it with whitespace, and convert to a lowercase the first character that appears after the Dh. So, for example, "GClass::DhF" will be converetd to "GClass f", and "GClass::DhY" will be converted to "GClass y". The idea is that instead of inputting <code>GClass \1</code>, I input what in LISP would be ( strcat "GClass " ( lowercaseString \1 ) ) – user1134991 Nov 21 '17 at 9:17
  • 2
    The place for such clarification is in the question. (Comments can be deleted at any time.) Please clarify the question. – Drew Nov 21 '17 at 19:32
2

Can I programmatically refer to a match or otherwise interpolate values in the replacement string?

Yes, see (emacs) Regexp Replace:

   You can use Lisp expressions to calculate parts of the replacement
string.  To do this, write ‘\,’ followed by the expression in the
replacement string.  Each replacement calculates the value of the
expression and converts it to text without quoting (if it’s a string,
this means using the string’s contents), and uses it in the replacement
string in place of the expression itself.  If the expression is a
symbol, one space in the replacement string after the symbol name goes
with the symbol name, so the value replaces them both.

For example, given the following buffer contents as per your example, where . represents point:

.GClass::Dh
GClass::DhFoo
GClass::Dhbar
GClass::DhBaz

executing:

C-M-%::Dh\(.\)?RET\,(if \1 (concat " " (downcase \1)) "")RET!

results in:

GClass
GClass foo
GClass bar
GClass baz

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.