0

I'm trying to parse weight, depth and height from the following string using regex '84" w x 39" d x 37" h'. I got success while scooping out weight and depth for it. However, I could not scrape the height in the right way. I know the patterns I've used might be very weak but it works for the first two fields.

I've tried with:

import re

rstr = '84" w x 39" d x 37" h'

weight = re.findall(r"(.*?)\"\s*?w",rstr)[0]
depth = re.findall(r"x\s*(.*?)\"\s*?d",rstr)[0]
height = re.findall(r"x\s*(.*?)\"\s*?h",rstr)[0]
print(weight,depth,height)

Output I'm getting:

84 39 39" d x 37

Output I wish to get:

84 39 37

The weight, depth and height may not always be in the same order.

How can I scrape the three fields from the above string using regex?

5
  • 1
    You should match digits explicitly, do not use .. x\s*(\d+(?:\.\d+)?)"?\s*h, see demo. Commented Jan 18, 2021 at 19:42
  • Or like \b(\d+)" \w x (\d+)" d x (\d+)" h\b regex101.com/r/02EQNV/1 to get all of them in a single pattern and then use the groups Commented Jan 18, 2021 at 19:43
  • Thanks a lot @Wiktor Stribiżew for your suggested pattern. It works perfectly. Commented Jan 18, 2021 at 19:55
  • Your pattern also works @The fourth bird. But, I wish to get them separately using individual pattern. Thanks. Commented Jan 18, 2021 at 19:58
  • @SMTH You can ideone.com/9QDhei Commented Jan 18, 2021 at 19:59

1 Answer 1

1

w, d, and h are not in same order, which makes one-line find all a bit hard, but probably still doable.

But for now, let us stick with one line for each:

re.findall(r'\d+(?=" w)',string)[0]
re.findall(r'\d+(?=" d)',string)[0]
re.findall(r'\d+(?=" h)',string)[0]

Here I also assumed you have integer number, and number of digits could vary. Basically what you really need IMO is a lookahead, a positive lookahead, which is (?=" d) in the search pattern.

By the way, the above matches are str right now, you may need int() it if any calculation is needed down the road.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.