Allow string-slice to take zero-length matches

* lisp/emacs-lisp/subr-x.el (string-slice): Allow zero-length
matches.  Code adapted from s.el by Magnar Sveen.
This commit is contained in:
Lars Ingebrigtsen 2020-12-23 07:45:19 +01:00
parent 21097cdd32
commit 22c1f00d99
2 changed files with 13 additions and 14 deletions

View file

@ -308,19 +308,16 @@ If OMIT-NULLS, empty lines will be removed from the results."
(defun string-slice (string regexp)
"Split STRING at REGEXP boundaries and return a list of slices.
The boundaries that match REGEXP are included in the result."
(let ((start-substring 0)
(start-search 0)
(result nil))
(save-match-data
(while (string-match regexp string start-search)
(if (zerop (match-beginning 0))
(setq start-search (match-end 0))
(push (substring string start-substring (match-beginning 0)) result)
(setq start-substring (match-beginning 0)
start-search (match-end 0))))
(push (substring string start-substring) result)
(nreverse result))))
The boundaries that match REGEXP are included in the result.
Also see `split-string'."
(if (zerop (length string))
(list "")
(let ((i (string-match-p regexp string 1)))
(if i
(cons (substring string 0 i)
(string-slice (substring string i) regexp))
(list string)))))
(defun string-pad (string length &optional padding start)
"Pad STRING to LENGTH using PADDING.