0

Use emacs-lisp, how to match the same variable assign statement?

for example:

below lines should be matched:

abc = abc
xyz = xyz
weeoof = weeoof

But below lines should not be matched:

abc = abd
xyz = zxy
weeoof = fwexxx

I am trying re-search-forward but don't know how to do it!

  • What do you really need to do? Regular expressions are not a good method for this - in fact, standard regexps cannot do this: you need some sort of extended regexps (one more reason not to use regexps). – NickD Oct 6 '18 at 22:51
  • @NickD Nobody's talking about the abstract mathematical concept of "regular expression", but about the similarly named "Emacs regexps", which has extra capabilities which make this not only possible, but easy too! – Omar Oct 7 '18 at 4:23
4

You can use back-references in the pattern, so you can search for:

^\(.+\) = \1

Note that \(.+\) = \1 (unanchored) would also match z = z and f = f in the second set of lines. You don't need to anchor to the start/end of the line to avoid this, but you do need some way to differentiate those cases. You might use \_< or even just \b in place of the ^ but it obviously depends upon the use-case.

See also C-hig (elisp)Regexp Backslash

  • Advocating the use of the rx macro: (rx (submatch word) "=" (backref 1)) – Heikki Oct 7 '18 at 6:28

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.