正则表达式重复模式

Regex repeated pattern

我正在尝试匹配以下模式:

((1.0 4) (2.0 5) .... (10.0 8))

元组(X N),其中X是一个带可选指数的浮点数,N是一个整数,可以重复多次。

我在 this 网站上尝试过,我可以为固定数量的元组生成正则表达式。例如,对于 2 个元组,我会得到

^\(\(([+-]?(?=\.\d|\d)(?:\d+)?(?:\.?\d*))(?:[eE]([+-]?\d+))?\s[0-9]+\)\s\(([+-]?(?=\.\d|\d)(?:\d+)?(?:\.?\d*))(?:[eE]([+-]?\d+))?\s[0-9]+\)\)$

如何修改模式,使元组的数量是任意的?我想我将不得不使用某种分组,但正则表达式对我来说很新。

您可以使用以下模式:

^\(\(\d+(?:\.\d+)? \d+\)(?:\s*\(\d+(?:\.\d+)? \d+\))*\)$

Demo

此模式匹配:

^
\(                             (
\(\d+(?:\.\d+)? \d+\)          a leading tuple
(?:\s*\(\d+(?:\.\d+)? \d+\))*  space, more tuples
\)                             )
$

"The tuple (X N), where X is a floating point number with optional exponent and N is an integer, can be repeated several times."

为了确保你有 1+ 个元组(带有可选的指数),你可以使用:

^\(\([-+]?\d*\.\d+([eE][-+]?\d+)?\s\d+\)(?:\s\([-+]?\d*\.\d+([eE][-+]?\d+)?\s\d+\))*\)$

在线查看demo


  • ^ - Start-line锚点;
  • \(\( - 两个字面左括号;
  • [-+]?\d*\.\d+([eE][-+]?\d+)? - 为了将您的 浮点数与可选指数 相匹配,我们匹配:一个可选的连字符或加号后跟 0+ 数字和一个带有 1 的文字点+ 数字。之后是可选的捕获组,用于将指数与字母 'e'、可选的连字符或加号和 1+ 位数字匹配;
  • \s\d+\) - 要完成元组,模式匹配:单个空白字符和 1+ 位数字以匹配右括号前元组的 integer 部分;
  • (?:\s.....)* - 下面的技巧是我们使用 non-capture 组来匹配单个空白字符和我们用于元组的模式。关闭此 non-capture 组时匹配它 0+ 次以允许任意数量的元组;
  • \)$ - 用文字结束括号和 end-line 锚点结束模式。

或者如果可用,捕获捕获组中的第一个元组并使用反向引用重复该确切模式:

^\((\([-+]?\d*\.\d+([eE][-+]?\d+)?\h\d+\))(?:\h(?1))*\)$

在线查看demo

您可以通过将字符串与以下正则表达式匹配来验证模式。

^\((?:\(\d+\.\d(?: \d+)?\)(?: |(?=\)$)))+\)$

Demo

正则表达式可以分解如下

^            # match beginning of string
\(           # match '('
(?:          # begin non-capture group
  \(         # match '('
  \d+\.\d    # match 1+ digits, '.', 1 digit
  (?: \d+)?  # optionally ('?') match a space then 1+ digits 
  \(         # match ')'
  (?:        # begin non-capture group
    [ ]      # match a space
    |        # or
    (?=\)$)  # positive lookahead asserts next char is ')' at end of string
  )          # end non-capture group
)+           # end non-capture group and execute one or more times
\)           # match ')'
$            # match end of string