只需安装s.el https://github.com/magnars/s.el字符串操作库并使用它s-suffix? https://github.com/magnars/s.el#s-ends-with-suffix-s-optional-ignore-case谓词:
(s-suffix? "turn." "...when it ain't your turn.") ; => t
但如果你拒绝使用这个库,你就必须编写自己的函数。有string-prefix-p https://www.gnu.org/software/emacs/manual/html_node/elisp/Text-Comparison.html#index-string_002dprefix_002dp-255,它类似于 Pythonstr.startswith http://docs.python.org/2/library/stdtypes.html?highlight=startswith#str.startswith, in subr.el
,它只是一个包装compare-strings https://www.gnu.org/software/emacs/manual/html_node/elisp/Text-Comparison.html#index-compare_002dstrings-256。根据Emacs 24.3 变更日志 https://www.gnu.org/software/emacs/news/NEWS.24.3:
** New function `string-prefix-p'.
(This was actually added in Emacs 23.2 but was not advertised at the time.)
string-suffix-p
was 仅在 Emacs 24.4 中添加 http://emacsredux.com/blog/2014/02/02/a-peek-at-emacs-24-dot-4-new-string-manipulation-functions/,所以对于早期版本我写道:
(defun string-suffix-p (str1 str2 &optional ignore-case)
(let ((begin2 (- (length str2) (length str1)))
(end2 (length str2)))
(when (< begin2 0) (setq begin2 0))
(eq t (compare-strings str1 nil nil
str2 begin2 end2
ignore-case))))
(when (< begin2 0) (setq begin2 0))
是一种解决方法,因为如果您将负数传递给compare-strings
,它呕吐*** Eval error *** Wrong type argument: wholenump, -1
.
如果你对函数进行字节编译,它的运行速度比伊夫·波姆斯 https://stackoverflow.com/users/83331/yves-baumes解决方案,尽管string-match
是一个C函数。
ELISP> (setq str1 "miss."
str2 "Ayo, lesson here, Bey. You come at the king, you best not miss.")
ELISP> (benchmark-run 1000000 (string-suffix-p str1 str2))
(4.697675135000001 31 2.789847821000066)
ELISP> (byte-compile 'string-suffix-p)
ELISP> (benchmark-run 1000000 (string-suffix-p str1 str2))
(0.43636462600000003 0 0.0)
ELISP> (benchmark-run 1000000 (string-match "miss\.$" str2))
(1.3447664240000001 0 0.0)