正则表达式捕获具有精确匹配和部分匹配的子组

时间:2016-05-22 07:28:33

标签: java regex

我有

input string : 
$data.store.author_handle.name0_handle[*].some.min()
regex :
^\$([a-zA-Z_0-9]+)(.[a-zA-Z_0-9.]+[\[\*0-9\]]*[.a-zA-Z_0-9]*)(.[min\(\)]*$)

所以我得到如下组:

  1. 数据
  2. .store.author_handle.name0_handle [*]。some.min
  3. ()
  4. 我想捕捉的地方如下

    1. 数据
    2. .store.author_handle.name0_handle [*]。一些
    3. .min()
    4. 请注意输入可以采用表格

      $<literal>.<json path> <aggregator function>
      <aggregator function> is optional and can be min/max/avg 
      <literal> : ([a-zA-Z_0-9]+)
      

      Json路径是https://github.com/jayway/JsonPath

      允许的任何路径

1 个答案:

答案 0 :(得分:1)

您可以使用以下正则表达式

^\$([\w]+)(\..+?)((?:\.(?:min|max|avg)\(\))?$)

<强> Regex Demo

正则表达式细分

^ #start of string
\$ #Match $ literally

( #Start of 1st capturing group
  [\w]+ #Match characters in set [A-Za-z0-9_] at least once(you can also use [^.]+)
) #End of 1st capturing group

( #Start of 2nd capturing group
  \. #Match . literally
  .+? #Match lazily till next condition is met
) #End of 2nd capturing group

( #Start of 3rd capturing group
  (?: #Non capturing group
    \. #Match . literally
      (?: #Non capturing group
         min|max|avg #Match any from min,max or avg
      )
    \(\) #Match () literally
  )? #As mentioned, this all can be optional(aggregation part)
  $ #End of string(Kept here so that if nothing matches 0 sized string is returned instead of null)
) #End of 3rd capturing group

^\$([\w]+)(\..+?)((?:\.(?:(?:\w+)\(\)))?$)

用于广义聚合函数

<强> Ideone Demo