简体   繁体   中英

How to capture recursive groups in a regex?

I am trying to capture a pattern which can appear multiple times in a regex in different groups. The pattern which can appear multiple times is :

(\b\\d{4}\\s*\\d{4}\\s*\\d{4}\\s*\\d{4}\b\\s*)

Please see complete test@ here !

The expected output should be :

Full Match:
Group1:1111 1111 1111 1111
Group2:2222 2222 2222 2222
... GroupN...

how can this be achieved ?

If I understand the problem correctly, we would be wishing for matching a four-digits and space pattern being repeated three times, followed by another four-digits, and we can likely start with a simple expression such as:

(\d{4}\s)\1\1(\d{4}\s?)

Demo 1

Or if we would be matching a four-digits pattern four times, and space three times, we would likely start with this expression:

(\d{4})(\s+)\1\2\1\2\1

Demo 2

RegEx Circuit

jex.im visualizes regular expressions:

在此处输入图片说明

Use:

(?:<select\b|\G).*?(\b\d{4}(?:\s*\d{4}){3}\b)(?=.*?</select>)

Demo

Explanation:

(?:                 # non capture group
  <select\b         # literally
  |                 # OR
  \G                # restart from previous match position
)                   # end group
.*?                 # 0 or more any character, you may use [\s\S]*?
(                   # start group 1
  \b                # word boundary
  \d{4}             # 4 digits
  (?:               # non capture group
    \s*             # 0 or more spaces
    \d{4}           # 4 digits
  ){3}              # end group, may appear 3 times
  \b                # word boundary
)                   # end group 1
(?=                 # lookahead, make sure we have aftre:
  .*?               # 0 or more any character
  </select>         # end tag
)                   # end lookahead

Sample code (php):

preg_match_all('~(?:<select\b|\G).*?(\b\d{4}(?:\s*\d{4}){3}\b)(?=.*?</select>))~', $html, $matches);
print_r($matches[1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM