[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
master 22c1f00 1/2: Allow string-slice to take zero-length matches
From: |
Lars Ingebrigtsen |
Subject: |
master 22c1f00 1/2: Allow string-slice to take zero-length matches |
Date: |
Wed, 23 Dec 2020 01:59:35 -0500 (EST) |
branch: master
commit 22c1f00d997d38ba0c453da5f5e9c526d0ac05b0
Author: Lars Ingebrigtsen <larsi@gnus.org>
Commit: Lars Ingebrigtsen <larsi@gnus.org>
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.
---
lisp/emacs-lisp/subr-x.el | 23 ++++++++++-------------
test/lisp/emacs-lisp/subr-x-tests.el | 4 +++-
2 files changed, 13 insertions(+), 14 deletions(-)
diff --git a/lisp/emacs-lisp/subr-x.el b/lisp/emacs-lisp/subr-x.el
index 09c4649..8a9424c 100644
--- a/lisp/emacs-lisp/subr-x.el
+++ b/lisp/emacs-lisp/subr-x.el
@@ -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.
diff --git a/test/lisp/emacs-lisp/subr-x-tests.el
b/test/lisp/emacs-lisp/subr-x-tests.el
index 854d61e..3fc5f1d 100644
--- a/test/lisp/emacs-lisp/subr-x-tests.el
+++ b/test/lisp/emacs-lisp/subr-x-tests.el
@@ -608,7 +608,9 @@
(should (equal (string-slice "foo-bar" "-") '("foo" "-bar")))
(should (equal (string-slice "foo-bar-" "-") '("foo" "-bar" "-")))
(should (equal (string-slice "-foo-bar-" "-") '("-foo" "-bar" "-")))
- (should (equal (string-slice "ooo" "lala") '("ooo"))))
+ (should (equal (string-slice "ooo" "lala") '("ooo")))
+ (should (equal (string-slice "foo bar" "\\b") '("foo" " " "bar" "")))
+ (should (equal (string-slice "foo bar" "\\b\\|a") '("foo" " " "b" "ar" ""))))
(ert-deftest subr-string-pad ()
(should (equal (string-pad "foo" 5) "foo "))