Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs Lisp: matching a repeated pattern in a compact manner?

Tags:

regex

emacs

elisp

Let's suppose I have an RGB string (format: #<2 hex digits><2 hex digits><2 hex digits>) like this:

"#00BBCC"

and I'd like to match and capture its <2 hex digits> elements in a more compact manner than by using the obvious:

"#\\([[:xdigit:]\\{2\\}]\\)\\([[:xdigit:]\\{2\\}]\\)\\([[:xdigit:]\\{2\\}]\\)"

I've tried:

"#\\([[:xdigit:]]\\{2\\}\\)\\{3\\}"

and:

"#\\(\\([[:xdigit:]]\\{2\\}\\)\\{3\\}\\)"

But the most they matched has been the first <2 hex digits> element.

Any idea? Thank you.

like image 351
Eleno Avatar asked Feb 01 '12 23:02

Eleno


1 Answers

You can make the regexp shorter at the expense of some extra code:

(defun match-hex-digits (str)
  (when (string-match "#[[:xdigit:]]\\{6\\}" str)
    (list (substring (match-string 0 str) 1 3)
          (substring (match-string 0 str) 3 5)
          (substring (match-string 0 str) 5 7))))
like image 126
Sean Avatar answered Oct 12 '22 23:10

Sean