How to get part of data with Regex

Viewed 39

I have an example which is :

[Unit] = 
[Diag] = Nilan zok-98
Alert danger C-00N47

[Unit] = 17B NORWAY 
[Diag] = Mobari-testing-17-AB
Pair num to get 17-9881 to be testing
Class nump

[Unit] = 
[Diag] = BLOC1 

I want to extract this example in two part like as below :

Match 1
Group 1.    [Unit] = 
Group 2.    [Diag] = Nilan zok-98
Alert danger C-00N47

Match 2
Group 1.    [Unit] = 17B NORWAY 
Group 2.    [Diag] = Mobari-testing-17-AB
            Pair num to get 17-9881 to be testing
            Class nump

Match 3
Group 1.    [Unit] = 
Group 2.    [Diag] = BLOC1 

I was using (.*\[Unit\].*\n).*(.*\[Diag].*) to get solution, but Diag section get always first line.

You find my test regex here : https://regex101.com/r/p6nLiK/1

1 Answers

You can use

(\[Unit\].*)\n(\[Diag].*(?:\n.+)*)

See the regex demo

Details:

  • (\[Unit\].*) - Group 1: [Unit] and the rest of the line
  • \n - a line feed char
  • (\[Diag].*(?:\n.+)*) - Group 2: [Diag], then the rest of the line and then zero or more non-empty lines.

A variation of the pattern is

(?m)^(\[Unit\].*)\n(\[Diag].*(?:\n\h*\S.*)*)

See this regex demo.

Here, (?m)^ matches any start of line position and \h*\S.* makes it match non-blank lines (\h* matches zero or more horizontal whitespace and \S matches any non-whitespace char). Replace \h with [\p{Zs}\t] or [^\S\r\n] if not supported.

Related