首页 > 解决方案 > Clojure RegEx:如何在正则表达式中嵌入注释?

问题描述

我正在寻找一种将注释嵌入到 Clojure 中的正则表达式中的方法,以解释这段或那段代码的作用。我在文档中找不到这样的功能。

在 Clojure 中有以下正则表达式:

 #"\$[A-Z]+|\((?:(?:\$[A-Z]+|[\w\'\-\_]+)(?:\|(?:\$[A-Z]+|[\w\'\-\_]+))*)\)"

如何在正则表达式中添加注释?在 Perl 中,我会坚持使用尾随/x修饰符,例如:

$_ =~ m/ abc    # some comment explaining what abc is about
         /x;

这使得几天后处理它变得容易。

我该如何在 Clojure 中进行操作?

标签: regexclojure

解决方案


您可以使用嵌入式标志选项(或内联修饰符(?x)

(str #"(?x)                          # Turn on COMMENTS mode
       \$[A-Z]+|                     # $ and 1+ ASCII letters or
       \(                            # ( char
          (?:                        # Start of a non-capturing group:
           (?:\$[A-Z]+|[\w'-]+)      # $ and 1+ ASCII letters or 1+ word, ' or - chars
           (?:                       # Start of a non-capturing group:
             \|(?:\$[A-Z]+|[\w'-]+)  # |, $ and 1+ ASCII letters or 1+ word, ' or - chars
          )*                         # End of the inner non-capturing group, repeat 0 or more times
         )                           # End of the outer non-capturing group
       \)                            # ) char
       "
)

注意

  • 由于使用的正则表达式引擎是 Java 引擎,所有文字正则空格, 即使在字符类中也必须转义。
  • 要在模式中使用文字#,请将其转义。

推荐阅读