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

问题描述 投票:0回答:2
我如何将所有Regexp匹配的位置存储在使用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等)的列表。  我觉得我一定缺少一些全球匹配的功能?  或者,也许有必要使用一段时间循环并向前搜索/向后搜索。

eDit

我最终写了此功能,但是我的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)

使用
match-string
regex emacs elisp
2个回答
0
投票

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

    
在适当的(e)lisp风格中,您的解决方案如下:

(defun my/match-positions (regexp str)
  "Find all positions where REGEXP matches in STR."
  (save-match-data
    (let ((res nil)
      (pos 0))
      (while (string-match regexp str pos)
    (push (setf pos (match-end 0))
          res))
      (nreverse res))))

0
投票

(require 'cl-lib) (defun my/match-positions (regexp str) "Find all positions where REGEXP matches in STR." (save-match-data (cl-loop for pos = 0 then (match-end 0) while (string-match regexp str pos) collect (match-end 0))))

or

(defun my/match-positions (regexp str) "Find all positions where REGEXP matches in STR." (save-match-data (cl-loop with pos = 0 while (string-match regexp str pos) collect (setf pos (match-end 0)))))

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.