john 517501
john 517501

Reputation: 77

Need the regex for this string in python?

I written regex for the particular string as mentioned below. match group(1) is including the values. I would need only the string portion rather than values.

import re

line = "dev_interface_values, 123 23, 8 1"
line2= "my_port_values2, 1234, 81"
m = re.search(r'^\s*(.+), (.*\S)\s*$', line)

print  m.group(1)
print  m.group(2)

m1 = re.search(r'^\s*(.+), (.*\S)\s*$', line2)

print  m1.group(1)
print  m1.group(2)

Output:

dev_interface_values, 123 23
8 1
my_port_values2, 1234
81

Expecting Output as :

m.group(1) -> dev_interface_values
m.group(2) -> 123 23, 8 1

m.group(1) -> my_port_values2
m.group(2) -> 1234, 81

Upvotes: 0

Views: 81

Answers (2)

TheMaster
TheMaster

Reputation: 50416

You just need to make first capture group lazy by using ?:

import re
line = "dev_interface_values, 123 23, 8 1"
line2 = "my_port_values2, 1234, 81"
for i in [line,line2]:
    m = re.fullmatch(r'^\s*(.+?), (.*\S)\s*$', i)
    print(m.group(1))
    print(m.group(2))

Upvotes: 1

jrd1
jrd1

Reputation: 10716

Try this regex (see it in action here):

^(\w+)\,\s*(.*\S)$

String 1 output:

dev_interface_values
123 23, 8 1

String 2 output:

my_port_values2
1234, 81

Upvotes: 0

Related Questions