22

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 special character that needs to be escaped or specified in some different way?

0

2 Answers 2

33

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.

Sign up to request clarification or add additional context in comments.

Comments

11

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))))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.