2

我想匹配所有标点符号,但不是“ '”,如“ I'm”。例如,在下面的句子中:

I'm a student, but I'm also working. 
 ^not match  ^match ^not           ^match

我可以使用“ [[:punct:]]+”来匹配所有标点符号,但我很难'从匹配模式中排除“”。

当然,我可以使用类似下面的一些东西来枚举表达,但这很繁琐,尤其是考虑到中文的所有标点符号。" [,.?!]"

请提出一个更优雅的解决方案。

提前致谢,

4

2 回答 2

3

如果您的正则表达式支持环视,您可以这样做:

(?!')[[:punct:]]

用简单的英语:如果向前看时没有单引号,则匹配任何标点符号

于 2009-12-12T22:02:57.203 回答
1

感谢巴特的回答和您的所有评论。受 Bart's 的启发,我检查了 emacs 似乎仍然不支持前瞻。但本着精神,我编写了以下代码:

(defun string-match-but-exclude (regexp string exclude & optional start)

“返回字符串中正则表达式的第一个匹配的开始索引,或 nil,但排除排除中的正则表达式。匹配忽略大小写,如果case-fold-search' is non-nil. If third arg start is non-nil, start search at that index in string. For index of first char beyond the match, do (match-end 0). 匹配结束'和'匹配开始'也给出与模式中括号结构匹配的子字符串的索引.

您可以使用函数 `match-string' 来提取与正则表达式中的括号结构匹配的子字符串。”

(让((数据为零))

(and (string-match regexp string start)

   ;; keep the match-data for recovery at the end. 

   (setq data (match-data))

   (not (string-match (concat "[" exclusion "]") (match-string 0 string)))

   (progn (set-match-data data) t) ; To recover the match data, and make sure it produces t as returned value

   (match-beginning 0)

   ))

)

所以对于 (?!')[[:punct:]] string "'") 的等价表达式

这将是

(字符串匹配但排除“[[:punct:]]”字符串“'”)

这可以完成这项工作,但不那么优雅。它应该是对 emacs 的一个小补充,以使其成为内置支持。

emacs 现在确实支持字符类。

再次感谢。

于 2009-12-19T14:36:57.423 回答