Emacs正则表达式匹配行尾,后跟新行

时间:2017-01-10 03:02:00

标签: regex emacs

对于正则表达式^$^J,空行后跟新行的匹配失败,但正则表达式^^J成功。前正则表达式有什么问题?

1 个答案:

答案 0 :(得分:4)

正则表达式中的

$通常匹配行尾的空字符串,但实际上只有$出现在正则表达式中的特定位置时才会出现这种情况(例如, regexp,或在子组的末尾,IIRC)。如果$出现在“中间”,则它只与$字符匹配。同样适用于^。例如。 (string-match "a^b$c" "1a^b$c2")返回1.

C-h i g (emacs) Regexps记录了这种行为:

‘^’
     is a special character that matches the empty string, but only at
     the beginning of a line in the text being matched.  Otherwise it
     fails to match anything.  Thus, ‘^foo’ matches a ‘foo’ that occurs
     at the beginning of a line.

     For historical compatibility reasons, ‘^’ can be used with this
     meaning only at the beginning of the regular expression, or after
     ‘\(’ or ‘\|’.

‘$’
     is similar to ‘^’ but matches only at the end of a line.  Thus,
     ‘x+$’ matches a string of one ‘x’ or more at the end of a line.

     For historical compatibility reasons, ‘$’ can be used with this
     meaning only at the end of the regular expression, or before ‘\)’
     or ‘\|’.