开发者

Elisp split-string function to split a string by . character

I am trying to split a string using 'split-string' function based on the . character. But (split-string "1.2.3" ".") doesn't work at all. It just returns a list of variable number of empty strings. Is . a sp开发者_如何转开发ecial character that needs to be escaped or specified in some different way?


Here is the official documentation for split-string function - https://www.gnu.org/software/emacs/manual/html_node/elisp/Creating-Strings.html

The second argument to the split-string function in (split-string "1.2.3" "\.") is a regular expression and as a result both the '.' character and '' character have special meaning. So the '.' character needs to be escaped and even the '' character needs to be escaped with another ''. (split-string "1.2.3" "\\.") will work fine as expected.


If you call describe-function on split-string, usually by pressing F1fsplit-stringEnter, you can see in the documentation, that the second parameter is not just a character, but a regular expression:

If SEPARATORS is non-nil, it should be a regular expression matching text which separates, but is not part of, the substrings. If nil it defaults to `split-string-default-separators', normally "[ \f\t\n\r\v]+", and OMIT-NULLS is forced to t.

While for most simple string operations Emacs built-in functions suffice, when you use string manipulation heavily in Elisp code, s.el third-party library is indispensable. You can install it via Emacs package manager, by running command package-install with s as a package name. Suppose you have multiple functions across several modules all doing something with strings, joining, splitting, capitalizing, comparing, trimming whitespace and so on. It makes sense to have all string related functions under a common namespace, so s.el's alternative to the built-in split-string would be s-split:

(s-split "\\." "1.2.3") ; ("1" "2" "3")

For example, if you need to transform string " 1-2-3 " into "3.2.1", you could write:

(s-reverse (s-join "." (s-split "-" (s-trim z))))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜