2

我熟悉正则表达式,但这个复杂的例子让我很吃惊。我试图了解这行代码在做什么:

r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/([gim]+\b|\B)'

这是一个试图检测正则表达式的代码片段,例如:/\s+/. 我理解它,直到嵌套[\[, 和(对应物。

(我需要将此代码从 Python 移植到 Java,并且无法理解上述代码的工作原理,以及为什么它不能像在 Java 中那样工作。)

4

1 回答 1

5

这是一个可能有帮助的分解版本:

/                      # Match an opening slash
(                      # Followed by one or more...
  \\.                  #    Backslash followed by any character
  |                    #   or...
  [^[/\\\n]            #    Something that's not a [, /, \, or newline
  |                    #   or...
  \[                   #    A literal [, followed by any number of...
    (
      \\.              #     backslashes followed by any character
      |                #     or...
      [^\]\\\n]        #     something that's not a ], \, or newline
    )*
  ]                    #    and ending with a ]
)+
/                      # And a closing slash
(
  [gim]+\b             # Followed by one or more of g, i, m
  |
  \B                   # or something that isn't a word boundary
)
于 2012-05-08T03:02:46.873 回答