Regulating Regex from a string with delimiters with sequential groups

I am trying to parse words from a delimited string and have capture groups in sequential order. eg

dog.cat.chicken.horse.whale

I know ([^.]+) That can parse every word, but that puts every line in capture group 1.

 Match 1 Full match 0-3 `dog` Group 1. 0-3 `dog` Match 2 Full match 4-7 `cat` Group 1. 4-7 `cat` Match 3 Full match 8-15 `chicken` Group 1. 8-15 `chicken` Match 4 Full match 16-21 `horse` Group 1. 16-21 `horse` Match 5 Full match 22-27 `whale` Group 1. 22-27 `whale` 

I really need something like

 Match 1 Full match 0-27 `dog.cat.chicken.horse.whale` Group 1. 0-3 `dog` Group 2. 4-7 `cat` Group 3. 8-15 `chicken` Group 4. 16-21 `horse` Group 5. 22-27 `whale` 

I tried several iterations without success, does anyone know how to do this?

+5
source share
1 answer

In this case, there is no good solution. All you could do was add optional non-capturing groups with captures to account for a certain number of groups.

So it might look like

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

etc. etc., just add more (?:\.([^.]+))? until you reach a certain limit that you must define.

See the demo of regex .

Note that you can bind a pattern to avoid partial matches:

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

^ matches the beginning of a line, and $ asserts a position at the end of a line.

0
source

Source: https://habr.com/ru/post/1274666/


All Articles