Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs lisp: get sub-matches from a regexp match

Tags:

emacs

elisp

I have a string variable somewhere in elisp code, and want to extract some parts of it into other variables using a regular expression with groupings. That's something that you can write in 1-2 lines in any language:

my ($user, $domain) = $email =~ m/^(.+)@(.+)$/;

How do I write the same in elisp?

like image 400
Artyom V. Kireev Avatar asked Apr 26 '13 18:04

Artyom V. Kireev


People also ask

What does regex (? S match?

(? s) for "single line mode" makes the dot match all characters, including line breaks. (? m) for "multi-line mode" makes the caret and dollar match at the start and end of each line in the subject string.

How do I match a regex pattern?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .

Does string match regex?

Java - String matches() Methodmatches(regex) yields exactly the same result as the expression Pattern.

What does $1 do in regex?

$1 is the first group from your regular expression, $2 is the second. Groups are defined by brackets, so your first group ($1) is whatever is matched by (\d+). You'll need to do some reading up on regular expressions to understand what that matches.


1 Answers

(save-match-data ; is usually a good idea
  (and (string-match "\\`\\([^@]+\\)@\\([^@]+\\)\\'" email)
       (setq user (match-string 1 email)
             domain (match-string 2 email) ) ))

The GNU Emacs Lisp Reference Manual is your friend. See also http://emacswiki.org/emacs/ElispCookbook

like image 166
tripleee Avatar answered Sep 29 '22 23:09

tripleee