Match word "A". If "B" is next word, match too

Viewed 58

Using regex in Python I want to get the word "net" from string and if the word "wt" is the next, get too

Example:

string = "12 boxes net wt 1.oz 3.6g" #Must returns "net wt"

string = "12 boxes net 1.oz 3.6g" #Must returns "net"

Between "net" and "wt" could be "." "," or spaces

I used this regex but didn't work on the second example

pat = r'net([,.\s]*?)(wt?)'

1 Answers

The pattern that you tried net([,.\s]*?)(wt?) captures a non greedy match from the character class and then matches a w with an optional t using the ? making only the w mandatory and could possible also match netw or net w

You could place the character class inside the parenthesis and make that whole part optional placing the ? after it.

\bnet(?:[,. ]wt)?\b

Regex demo

Related