Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match {12} digit number & other pattern, multiline, when any characters can be between them

Tags:

regex

I am trying to create a regex, but I am not sure at this point, if it is possible:

As my example: https://regex101.com/r/JRBYyw/6

Requirements:

  • I need regex to match 12 numbers
  • after or before 12 numbers there can be ANY characters in multiple - different amount of lines
  • I want to match pattern [A-Z]{4}\s?\d{7} which can be after 12 digit number random-amount of times (between them again, random other characters in multiple lines)
  • I want to match [A-Z]{4}\s?\d{7} so many times, until there is another 12 digit number somewhere in the text before it - not only directly before it, but between other text again.
  • If it helps we can assume that 12 digit number and A-Z pattern will be on a new line, at the start of it.
like image 250
Jane9256 Avatar asked Nov 19 '25 10:11

Jane9256


1 Answers

You can use a two-pass approach: 1) extract all blocks of texts that start with 12-digit numbers and span up to the next 12-digit number or end of text, and 2) then extract the letter-digit patterns from each block.

Here is the first regex:

^(3\d{11})\R+([\s\S]*?)(?=\R3\d{11}|\z)

See the regex demo. The 12-digit numbers are in Group 1 here. Then, take Group 2 as input for

\d{12}|[a-zA-Z]{4}\s?\d{7}

that matches either 12 digits, or four letters, an optional whitespace and then seven digits.

See this regex demo

like image 87
Wiktor Stribiżew Avatar answered Nov 21 '25 02:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!