简体   繁体   中英

Beginning and end of the string in Emacs regexps

What is the characters that indicate the beginning and the end of the string with newlines in it? I'm writing a trim function:

(defun trim (str)
  (if (string-match "^[[:space:]]*\\(.+?\\)[[:space:]]*$" str)
      (match-string 1 str)
      str))

But with a string like "first/nnext" (got from shell-command-to-string ) it returns only the "first". Reference manual says:

When matching a string instead of a buffer, '^' matches at the beginning of the string or after a newline character.

\\\\' and the left one are for beginning/end of a buffer, so it simply returns nothing from a string. Therefore, how to indicate the 'absolute' beginning of a string, if possible?

It's \\\\` for beginning of buffer or string. And \\\\' for end. See manual

However, I think the root of your confustion isn't the anchor. The [:space:] char class matches different characters based on the current syntax table. To reliably match a non-printing or printing character use [:graph:] . See char class

Also . won't match newlines.

Eg

(let ((str " \n a\nbc \n "))
  (string-match "\\`[^[:graph:]]*\\(\\(?:.\\|\n\\)+?\\)[^[:graph:]]*\\'" str)
  (match-string 1 str))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM