Emacs Lisp: matching a repeating pattern in a compact way?

Suppose I have an RGB string (format: # <2 hex digits> <2 hex digit> <2 hex digitits>) as follows:

"#00BBCC"

and I would like to match and remove its <2 hex digits> elements in a more compact way than using the obvious:

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

I tried:

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

and

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

But most of them are the same, this is the first element <2 hex digit>.

Any idea? Thank.

+5
source share
2 answers

If you want to capture R, G, B in different subgroups, so that you can extract them with (match-string group), at some point you need to have three groups of parentheses in your regular expression.

\(...\)\(...\)\(...\)

Otherwise, if you use a repeat pattern, for example

\(...\)\{3\}

, . , , -

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

"A0B1C2", (match-string 1) , "C2", .

, : , , , , , , , , .

, -

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

, .

+1

regexp :

(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))))
+4

All Articles