Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

Finding in-between 2 consecutive numbers (regEx)

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
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)

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use

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

See the regex demo.


  • ^ - 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)
  • (.*(?: ? (?!d+ +([a-z]+)).*)*) - Group 1:
    • .* - the rest of the line
    • (?: ? (?!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 ).

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share