sam
sam

Reputation: 115

How do I create a regex in Emacs to capture text between double square brackets?

I want to create a regex in Emacs that captures text between double square brackets.

I found this regex. It allows to find string betwen square brackets but it includes the square brackets :

"\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"

How can extract the string between double square brackets excluding the square brackets?

Upvotes: 3

Views: 2181

Answers (3)

legoscia
legoscia

Reputation: 41528

To extract data from a string, use string-match and match-string, like this:

(let ((my-string "[[some text][some more text]]")
      (my-regexp "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"))
  (and (string-match my-regexp my-string)
       (list (match-string 1 my-string) (match-string 3 my-string))))

which evaluates to:

("some text" "some more text")

To extract data from a buffer, use search-forward-regexp and drop the string argument to match-string:

(and
 (search-forward-regexp "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]" nil :no-error)
 (list (match-string 1) (match-string 3)))

Note that this moves point to the match.

Upvotes: 1

Nicolas Dudebout
Nicolas Dudebout

Reputation: 9262

This regexp will select the square brackets but by using group 1 you will be able to get only the content: "\\[\\[\\(.*\\)\\]\\]"

Upvotes: 6

event_jr
event_jr

Reputation: 17707

You cannot. Emacs' regexp engine does not support look-ahead/look-behind assertions.

As a work, around, just group the part you're interested in and access the subgroup.

Upvotes: 3

Related Questions