Vincent W.
Vincent W.

Reputation: 5

Regex into variables

I use a regex101.com#python and here are my strings:

Regular Expression:

.* src=.(?<Pvar1>\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}).* dst=.(?<Pvar2>\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})

Test String:

k=57829.57892gfjhfg.tur90eunn 4538.333.3 user="JHenry" src="10.10.1.21" dst="10.10.20.42" ttubbies="yellow"]

I try to transpose this to my code, but I have no clue on how to do this. How do I get var1 and var2 in Python and print them?

I tried print(var1) without any success.

Upvotes: 0

Views: 80

Answers (2)

Paul Ellsworth
Paul Ellsworth

Reputation: 106

I would do something like this.

import re
string = 'k=57829.57892gfjhfg.tur90eunn 4538.333.3 user="JHenry" src="10.10.1.21" dst="10.10.20.42" ttubbies="yellow"]'
results = re.match(".* src=.(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}).* dst=.(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})", string)
print results.group(1)
print results.group(2)

Example output:

$ python t.py
10.10.1.21
10.10.20.42

Upvotes: 0

Barmar
Barmar

Reputation: 782785

Capture groups are accessed using the group() method of the Match object that re.match returns. If you use normal capture groups, the argument is the group number; if you use named capture groups the argument is the name.

str = 'k=57829.57892gfjhfg.tur90eunn 4538.333.3 user="JHenry" src="10.10.1.21" dst="10.10.20.42" ttubbies="yellow"]'
regexp = r'.* src=.(?<Pvar1>\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}).* dst=.(?<Pvar2>\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})'
match = re.match(regexp, str)
pvar1 = match.group('Pvar1')
pvar2 = match.group('Pvar2')

See the documentation of Match objects.

Upvotes: 4

Related Questions