4

According to https://www.emacswiki.org/emacs/RegularExpression#regexp

 \(\w+\) +\1\>       

finds two consecutive identical words. It works if the words are in the same line separated by an arbitrary number of white spaces. How to find consecutive identical words not necessarily in the same line by a regexp? According to the link above

\(\<\w+\>\)\s-+\1

can do the job. But I don't know why it cannot find the duplicate words file file below

;; This buffer is for notes you don't want to save, and for Lisp evaluation.
;; If you want to create a file, visit that file  
file with C-x C-f,
;; then enter the text in in that file's own buffer.

1 Answer 1

6

\s- matches a whitespace character. A newline character can have whitespace syntax in some modes, but often it does not. Many programming modes change the syntax of newlines to that of a comment end, for instance. So your regexp works in Text mode but not in Lisp interaction mode (used in *scratch*, for instance).

Use this interactively, where the newline char is inserted using C-q C-j:

\(\<\w+\>\)\(\s-\|
\)+\1\>

Or use this in Lisp (it is equivalent): \\(\\<\\w+\\>\\)\\(\\s-\\|\n\\)+\\1\\>

For example:

(re-search-forward "\\(\\<\\w+\\>\\)\\(\\s-\\|\n\\)+\\1\\>")
2
  • You might want to put a "\b" at the end, or it will match things where the first word in the second line has a prefix of the last word in the first line. For example, "this is an\nanomoly" will be matched by the current regexp, but not by \\(\\<\\w+\\>\\)\\(\\s-\\|\n\\)+\\1\\b.
    – zck
    Aug 20, 2016 at 19:27
  • 1
    @zck: Thanks; updated (used \\w).
    – Drew
    Aug 20, 2016 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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