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?
(? 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.
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 "(" .
Java - String matches() Methodmatches(regex) yields exactly the same result as the expression Pattern.
$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.
(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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With