写成长长的正则表达式,嵌入评论的成语? [英] go idiom for writing long regular expressions, embedded comments?

查看:130
本文介绍了写成长长的正则表达式,嵌入评论的成语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些语言可以在长正则表达式中嵌入换行符和空格,以提高可读性。



$ p $ (yogi | booboo) #匹配
\ $
(\s)? #可选文章
熊#熊不是Mr. Ranger

AFAICT golang does 不是有这个选项,是吗?



缺乏这个,是一个组合正则表达式是唯一的选择为了清晰?或者还有另一个成语吗?

解决方案

大多数情况下,人们只是提供一个评论描述正则表达式匹配的内容。但是通过浏览Go源代码,我发现 一个有趣的例子:

$ $ p $ // removeRE是在
/ /消息时查找消息文本。
var removeRE = regexp.MustCompile(`(?ms)\A(`+
//跳过领先的Hello so-and-so,由codereview插件生成。
`(你好(。| \\\
)*?\\\
\\\
)`+

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

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

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

`)`,


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.

解决方案

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)` +

    `)`,
)

这篇关于写成长长的正则表达式,嵌入评论的成语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆