0

To match with multiple line regexp, I can use \\(.*\\|\n\\), but I think it should be [.*\\|\n\\] which actually doesn't work as expected.

#+NAME: exam1
#+BEGIN_SRC elisp :results output
(let ((str "")
      (start 0))
  (setq str "this is\na test and this is a test")
  (while (string-match "this is\\(.*\\|\n\\)a test" str start)
    (setq start (match-end 0))
    (print (match-string 0 str))))

#+END_SRC

#+RESULTS:
: 
: "this is
: a test"
: 
: "this is a test"

#+NAME: exam2
#+BEGIN_SRC elisp :results output
(let ((str "")
      (start 0))
  (setq str "this is\na test and this is a test")
  (while (string-match "this is[.*\\|\n]a test" str start)
    (setq start (match-end 0))
    (print (match-string 0 str))))

#+END_SRC

#+RESULTS: exam2
: 
: "this is
: a test"

What's the reason exam1 works but exam2 doesn't?

3
  • 2
    Have you read (elisp) Syntax of Regexps?
    – npostavs
    Sep 30, 2017 at 15:44
  • 1
    What @npostavs said. The reason your second regexp doesn't "work" is that you are expecting it to match something that it, as a regular expression, should not match. [.*\\|\n\\] matches a single character - any of these characters: .*\| (period, asterisk, backslash, vertical bar) or a newline character.
    – Drew
    Sep 30, 2017 at 20:45
  • 1
    @lucky1928 Can you tell us why you think that square brackets should work that way? Like wasamasa, I've never encountered any regexp dialect where that would be true, so I'm very interested in how you came to this understanding.
    – phils
    Sep 30, 2017 at 22:02

1 Answer 1

1

I haven't heard of any implementation of regular expression where character alternatives ([...]) would permit alternation (|) as that construct only makes sense inside groups ((...)). Remember that character alternatives are interpreted as one of the included characters matching a character ([abc] matches a, b or c), whereas alternation means that a sequence must match any of the enclosed sequences (\\(foo\\|bar\\) matches foo or bar).

Your Answer

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

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