Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex capture group that precedes or follows another capture group

Tags:

regex

I'm trying to create a capture group that could precede or follow another capture group.

Given:

TAKE 4 MG BY MOUTH
INHALE 14 PUFFS
4 PUFFS INHALE

Wanted:

qty unit  rte
--- ----  ---
4   MG    BY MOUTH
14  PUFFS INHALE
4   PUFFS INHALE

My attempt, (?:(?'qty'\d+)\s(?'unit'(PUFFS|MG))).*(?'rte'(BY MOUTH|INHALE)), works only when the rte follows the qty/unit group. What is this concept called? A "look-around"?

Example: https://regex101.com/r/IRTYgU/1

like image 575
craig Avatar asked Oct 22 '25 08:10

craig


1 Answers

You can use

^(?=.*(?'rte'BY MOUTH|INHALE)).*\b(?'qty'\d+)\s(?'unit'PUFFS|MG)

See the regex demo.

Details:

  • ^ - start of string
  • (?=.*(?'rte'BY MOUTH|INHALE)) - after any zero or more chars other than line break chars as many as possible, there must be either BY MOUTH or INHALE (Group "rte")
  • .* - any zero or more chars other than line break chars as many as possible
  • \b - a word boundary (to match the digits as a full number)
  • (?'qty'\d+) - Group "qty": one or more digits
  • \s - a whitespace
  • (?'unit'PUFFS|MG) - Group "unit": PUFFS or MG
like image 106
Wiktor Stribiżew Avatar answered Oct 23 '25 22:10

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!