【发布时间】:2015-07-14 17:15:48
【问题描述】:
如何使用 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)
【问题讨论】:
-
我不相信有一个内置的方法可以做你想做的事。您的代码看起来很合适,尽管检查
(< os (length str))应该是多余的 b/cstring-match在未找到匹配项时已经返回nil。那和 lisp 风格是在表达式的最后一行关闭括号,而不是单独在行上。