【问题标题】:Get all positions of regexp matches in string获取字符串中正则表达式匹配的所有位置
【发布时间】: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)

【问题讨论】:

  • 我不相信有一个内置的方法可以做你想做的事。您的代码看起来很合适,尽管检查 (&lt; os (length str)) 应该是多余的 b/c string-match 在未找到匹配项时已经返回 nil。那和 lisp 风格是在表达式的最后一行关闭括号,而不是单独在行上。

标签: regex emacs elisp


【解决方案1】:

使用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
          )))

【讨论】:

  • 这只能找到一个匹配项吗?我真的不明白这是如何给出匹配的
猜你喜欢
  • 2013-06-12
  • 1970-01-01
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 2012-03-23
  • 2011-02-10
相关资源
最近更新 更多