开发者

Syntax of emacs replace-regexp

I'm trying to find every date and put quotes around it. I thought this should be:

M-x replace-regexp开发者_高级运维 201\d-\d\d-\d\d <ret> '\&'

I also tried [0-9] instead of \d.

it doesn't work. But using isearch-forward-regexp I can type [0-9][0-9] and watch the targets highlight. What am I doing wrong with the replace?


Emacs regexps don't have the common \d shorthand for [0-9].

I just put the text 2011-04-01 into a new buffer, went back to the start of the buffer, and typed M-x replace-regexp RET 201[0-9]-[0-9][0-9]-[0-9][0-9] RET '\&' RET, and the date was surrounded by single quotes, as expected.


\d is not supported in Emacs regular expression syntax (C-h S regexp has documentation on them). You can use [0-9] as you did, or use the POSIX style [[:digit:]].

However, what you did (with [0-9]) should have worked, and did in fact just work for me. If you're using a regular expression in a program you might also find M-x regexp-builder useful.


You may need to escape the -s:

M-x replace-regexp <RET> 201[0-9]\-[0-9][0-9]\-[0-9][0-9] <RET> '\&'


The regexps given are overly inclusive. The following will also match invalid dates, like "2014-01-33", but not as many (assumes YYYY-MM-DD ordering):

"^20[0-9][0-9]-[0-1][0-2]-[0-3][0-9]"

or, to avoid dates like "2014-11-33" (but not like "2014-02-31" or "2014-00-00"), you could be slightly more restrictive:

"^20[0-9][0-9]-[0-1][0-2]-\([0-2][0-9]\|30\|31\)"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜