正则表达式匹配中\>的问题

欲用正则表达式 apple\S-+\> 来匹配,结果如下,为什么第一行只能匹配到 apple_tree[31:0 :sweat:

(elisp) Regexp Backslash:

‘\>’
     matches the empty string, but only at the end of a word.  ‘\>’
     matches at the end of the buffer (or string) only if the contents
     end with a word-constituent character.

“123abc” 中的字符是 word-constituent 字符,“_[:]” 中的则不是,所以以 \> 结尾的正则表达式所匹配到的内容不可能以字符 ] 结尾。

是说[:]这三个字符都不是word?那为什么不是到apple_tree结束,是因为\S

‘\Scode’ matches any character whose syntax is not code.

么?

正解,[ 和 :都属于 \S- 的范畴。

看漏了

‘\scode’ To represent whitespace syntax, use either ‘-’ or a space character.

还是没明白,\s-\S-分别会匹配什么?

\s- 匹配空格 \S- 匹配非空格

哦明白了,]不是word,所以0]的边界可以作为\>,但是[也不是word吧,为什么没匹配到apple_tree

(咦,绕了一圈怎么又问出了上面问过的问题。。

但是\S- 在 \>之前,所以先匹配非空格。

这三个子串均满足

  • apple_tree
  • apple_tree[31
  • apple_tree[31:0

+ 返回的是最长的。改用 +? 的话返回最短的,即 apple_tree

(let ((s "apple_tree[31:0] one"))
  (string-match "apple\\S-+\\>" s)
  (match-string 0 s))
     => "apple_tree[31:0"

(let ((s "apple_tree[31:0] one"))
  (string-match "apple\\S-+?\\>" s)
  (match-string 0 s))
     => "apple_tree"
2 个赞

哦对,正则默认是贪婪的