获取字符串中regexp匹配的所有位置

时间:2015-07-14 17:15:49

标签: regex emacs elisp

如何使用elisp将所有正则表达式匹配的位置存储在字符串中?下面是一个示例,我希望获得字符串中单词/数字的所有末尾的位置,或者如果是单引号,则是单引号短语的结尾。

(setq str "1  '2015-08-14 7:11:00'     GAR -0.29 89.10 -0.2795       0.375       8 0.6026 155.430000000          'GA Obler' 2015-08-14")

(string-match "\\b" str -1)  ; gets the last match

因此,此示例应返回(1,23等)的列表。我觉得我必须缺少一些全局匹配的功能?或者,可能需要使用while循环并向前/向后搜索。

修改

我最后编写了这个函数,但是我的elisp非常糟糕所以问题仍然存在,这是否是正确的方法 - 或者是否有另外的内置函数可以做到这一点?

(defun match-positions (regexp str)
  (let ((res '()) (pos 0))
    (while (and (string-match regexp str pos)
        (< pos (length str) ) )
      (let ((m (match-end 0)))
    (push m res)
    (setq pos m)
    ) )
    (nreverse res)
    )
  )
(match-positions "\'.*?\'\\|[-0-9.A-Za-z]+" str)
; (1 23 31 37 43 51 63 71 78 92 112 123)

1 个答案:

答案 0 :(得分:0)

使用match-string

(setq str "1  '2015-08-14 7:11:00'     GAR -0.29 89.10 -0.2795       0.375       8 0.6026 155.430000000          'GA Obler' 2015-08-14")

(save-match-data
    (and (string-match "\\b" str)
         (let ((first_match (match-string 0 str))
               (second_match (match-string 1 str))
              )
           ;; your code
          )))