Finding in-between 2 consecutive numbers (regEx)

Viewed 56

I have bee trying to create a exam paper parser. I am struggling to make a regular expression for capturing the question in-between 2 consecutive numbers. Here is a sample of the paper:

21 (a) (i) Protons Neutrons Electrons
29 Si 14
1
22 (a) (i) Oxidised

I would like to capture the 21 and (a) (i) Protons Neutrons Electrons 29 Si 14 16 14 1 in this example.

Here is my attempt https://regex101.com/r/dlESTV/3 I am finding this very difficult, because the expression will capture everything in-between the 21 and 29 (instead of 22)

1 Answers

You can use

^(\d+) (.*(?:\r?\n(?!\d+ +\([a-z]+\)).*)*)

See the regex demo.

Details:

  • ^ - start of a line
  • (\d+) - Group 1: one or more digits
  • - a space (you may add + after the space, but it is only necessary if you need to make sure there is a ( after it)
  • (.*(?:\r?\n(?!\d+ +\([a-z]+\)).*)*) - Group 1:
    • .* - the rest of the line
    • (?:\r?\n(?!\d+ +\([a-z]+\)).*)* - zero or more lines that do not start with
      • \d+ - one or more digits
      • + - one or more spaces
      • \([a-z]+\) - a (, then one or more lowercase ASCII letters, then ).
Related