编写长正则表达式时,嵌入注释的惯用语是什么?

huangapple go评论83阅读模式
英文:

go idiom for writing long regular expressions, embedded comments?

问题

一些语言提供了在长正则表达式中嵌入换行符和空格的功能,以使其更易读。

( yogi | booboo )   # 匹配某些内容
\s
( the \s)?          # 可选的冠词
bear                # 熊不是 Ranger 先生

据我所知,Go语言(golang)没有这个选项,是这样吗?

如果没有这个选项,是不是只能使用组合正则表达式来提高可读性?还是还有其他的习惯用法?我现在找不到任何关于Go中长正则表达式的示例。

英文:

Some languages have facilities for embedding newlines and whitespace in long regular expressions to make them more readable

( yogi | booboo )   # match something
\s
( the \s)?          # optional article
bear                # bears are not Mr. Ranger

AFAICT golang does not have that option, is that right?

Lacking that, is a composed regex the only option for clarity? Or is there another idiom? I'm not finding any examples of long regexen in go right now.

答案1

得分: 8

大多数时候,人们只是提供一个带有正则表达式匹配描述的注释。但是在浏览 Go 源代码时,我找到了这个有趣的例子:

// removeRE 是在查找消息文本时要跳过的模式列表。
var removeRE = regexp.MustCompile((?m-s)\A( +
// 跳过由 codereview 插件生成的“Hello so-and-so,”开头的内容。
(Hello(.|\n)*?\n\n) +

// 跳过引用的文本。
`|((On.*|.* writes|.* wrote):\n)` +
`|((>.*\n)+)` +

// 跳过没有字母的行。
`|(([^A-Za-z]*\n)+)` +

// 跳过指向评论和文件信息的链接。
`|(http://codereview.*\n([^ ]+:[0-9]+:.*\n)?)` +
`|(File .*:\n)` +

`)`,

)

英文:

Most of the time people just provide a comment with a description of what the regexp matches. But skimming through the Go source code I have found this interesting example:

// removeRE is the list of patterns to skip over at the beginning of a
// message when looking for message text.
var removeRE = regexp.MustCompile(`(?m-s)\A(` +
	// Skip leading "Hello so-and-so," generated by codereview plugin.
	`(Hello(.|\n)*?\n\n)` +

	// Skip quoted text.
	`|((On.*|.* writes|.* wrote):\n)` +
	`|((>.*\n)+)` +

	// Skip lines with no letters.
	`|(([^A-Za-z]*\n)+)` +

	// Skip links to comments and file info.
	`|(http://codereview.*\n([^ ]+:[0-9]+:.*\n)?)` +
	`|(File .*:\n)` +

	`)`,
)

huangapple
  • 本文由 发表于 2014年7月6日 00:23:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/24588352.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定