user2003052
user2003052

Reputation: 119

Regex to separate digits after =

I am trying to create three groups within Python from the following string.

Step 0rd, 2: Stop 0rd, 0id Vnsd=264rd L_RD_Gs=10

The first digit group is the ID number, then the following groups should be the digits that appear after the two equals signs.

I've created the following Regex which gives me the ID number and the digits '10' appearing after the second equal sign. I've tried adding a second = in my regex but that didn't work for me. ^(.*?)(\d*)id\s*(.*?).*=(\d*).*$

How to I extend what I have to create the second group to isolate the digits '264' after the first equals sign?

https://regex101.com/r/nFVs8c/1

Edit: My expected output from the provided text would be 0 264 10. I'm getting the 0 and the 10, struggling with the 264. Note my current regex has a group at the beginning of the text which I've left in my regex but can be disregarded.

Upvotes: 0

Views: 73

Answers (3)

user2003052
user2003052

Reputation: 119

Of course I worked out my error right after posting... ^(.*?)(\d*)id\s*(.*?).*=(\d*).*=(\d*).*$ works for what I am attempting.

Having said that I think what Tim has offered up is a nice alternative. And the answer provided by Andrej looks useful for my implementation.

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195438

If the number of groups is dynamic, you can split your regex:

import re

s = 'Step 0rd, 2: Stop 0rd, 0id Vnsd=264rd L_RD_Gs=10'

id_ = re.search(r'(\d+)id', s).group(1)
groups = dict(re.findall(r'([^\s]+)=(\d+)', s))

print(id_)
print(groups)

Prints:

0
{'Vnsd': '264', 'L_RD_Gs': '10'}

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521259

One simple approach here would be to use re.findall with an appropriate regex pattern, e.g.

inp = "Step 0rd, 2: Stop 0rd, 0id Vnsd=264rd L_RD_Gs=10"
matches = re.findall(r'.*(\d+)id\b [^=]+=(\d*)\S* [^=]+=(\d*)\S*', inp)
print(matches)

This prints:

[('0', '264', '10')]

Upvotes: 1

Related Questions