tags:

views:

155

answers:

3

Hi,

I'm trying to match a string and then use grouping to create a new string:

  (let ((url (browse-url-url-at-point)))
    (if (string-match "http://domain/\\([0-9]+\\)/\\([a-z]+\\)\.\\([0-9]+\\)" url)
  (setq filename (concat (match-string 1 url) "_" (match-string 2) "." (match-string 3) ".xml"))))

When I (print url) I get the following

"http://domain/1234/action.1234567"

When I (print filename) after a successful match I get the following:

#("1234_ublish.eport s.xml" 0 5 nil 5 11 (face nxml-element-local-name-face fontified t) 11 12 nil 12 17 (face nxml-element-local-name-face fontified t) 17 18 (fontified t) 18 19 (face nxml-attribute-local-name-face fontified t) 19 23 nil)

Why is this happing?

+3  A: 

You didn't include the optional string parameter for your second and third match-string's. Per the match-string documentation "string should be given if the last search was by `string-match' on string."

mamboking
+1  A: 

I found the problem.

It turns out that (string-match) needs to take the original string as an argument, or else it returns this weird list containing strange values (not sure what these are).

At any rate, changing about code to this:

 (let ((url (browse-url-url-at-point)))
    (if (string-match "http://domain/\\([0-9]+\\)/\\([a-z]+\\)\.\\([0-9]+\\)" url)
  (setq filename (concat (match-string 1 url) "_" (match-string 2 url) "." (match-string 3 url) ".xml"))))

Fixes the problem

oneself
A: 

As mamboking already mentioned, the docstring of match-string tells you all about:

(match-string NUM &optional STRING)
 ⋮
STRING should be given if the last search was by `string-match' on STRING.

If you also check string-match's documentation, you'll see that it suggests to use match-beginning and match-end to get the matches. These are built-in functions in C.

(if (string-match "\\([a-z]\\)" "123 test string")
  (match-beginning 1)) ;; 4

These functions only return the position of start or end of the text matched, that's why match-string needs the original string, too. When using search-forward or re-search-forward, match-beginning and match-end will return buffer positions, so match-string can easily substring the interesting matches from buffer's content.

You may also want to take a look at match-string-no-properties which behaves the same as match-string expect it returns string of text matched without text properties.

Török Gábor