I have been searching everywhere in the emacs lisp documentation for how to regular expressions search into a string. All I find is how to do this in buffers.
Is there something I'm missing? Should I just spit my string into a temporary buffer and search for it there? Is this just the coding style of elisp, something I'll get used to? Is the开发者_运维百科re a standard solution to this problem. Manipulating buffers seems cludgy when I should just be able to search straight into a variable already present.
Here is a discussion of string content vs buffer content in the Emacs wiki. Just store your string as a variable.
The tricky thing about strings is that you generally do not modify the string itself (except if you perform array functions on string, since a string is an array, but this should generally be avoided), but you return the modified string.
At any rate, here is an example of using a string in elisp.
This will trim the whitespace from the end of a string:
(setq test-str "abcdefg ")
(when (string-match "[ \t]*$" test-str)
(message (concat "[" (replace-match "" nil nil test-str) "]")))
The function you're looking for is string-match
. If you need to do the matching repeatedly, use the index it returns as the optional "start" parameter for the next call. The documentation is in the ELisp manual, chapter "Regular Expression Searching".
To replace every regexp match in a string take a look at replace-regexp-in-string
.
To search the beginning of a string
(defun string-starts-with-p (string prefix)
"Return t if STRING starts with PREFIX."
(and
(string-match (rx-to-string `(: bos ,prefix) t)
string)
t))
To search the end of a string
(defun string-ends-with-p (string suffix)
"Return t if STRING ends with SUFFIX."
(and (string-match (rx-to-string `(: ,suffix eos) t)
string)
t))
精彩评论