Mir*_*lov 9 string emacs elisp substring string-matching
是否有一个函数检查字符串是否以某个子字符串结尾?Python有endswith:
>>> "victory".endswith("tory")
True
Run Code Online (Sandbox Code Playgroud)
只需安装s.el字符串操作库并使用其s-suffix?谓词:
(s-suffix? "turn." "...when it ain't your turn.") ; => t
Run Code Online (Sandbox Code Playgroud)
但如果您拒绝使用此库,则必须编写自己的函数.有string-prefix-p,这是一个模拟Python的str.startswith,在subr.el和它只是一个围绕包装compare-strings.根据Emacs 24.3更改日志:
** New function `string-prefix-p'.
(This was actually added in Emacs 23.2 but was not advertised at the time.)
Run Code Online (Sandbox Code Playgroud)
string-suffix-p是只在Emacs 24.4增加,因此对于早期版本我写道:
(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))))
Run Code Online (Sandbox Code Playgroud)
(when (< begin2 0) (setq begin2 0))是一种解决方法,因为如果你传递负数compare-strings,它就是barfs *** Eval error *** Wrong type argument: wholenump, -1.
如果你对字节进行字节编译,它的工作速度比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)
Run Code Online (Sandbox Code Playgroud)
您可以使用正则表达式调用该string-match函数.
(if (string-match "tory\\'" "victory")
(message "victory ends with tory.")
(message "victory does not ends with tory."))
Run Code Online (Sandbox Code Playgroud)