Beginning and end of the string in Emacs regexps

别来无恙 提交于 2019-12-07 16:39:45

问题


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?


回答1:


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.

E.g.

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


来源:https://stackoverflow.com/questions/7572411/beginning-and-end-of-the-string-in-emacs-regexps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!