Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reuse regular expression

I have to match a text.

Ej:

text = 'C:x=-10.25:y=340.1:z=1;'

Where the values after x,y or z accept values matched by:

-?\d{1,3}(\.\d{1,2})?

How can i reuse that?

Those are the only values that are variables. All others characters must be fixed. I mean, they must be in that exact order.

There is a shorter way to express this?

r'^C:x=-?\d{1,3}(.\d{1,2})?:y=-?\d{1,3}(.\d{1,2})?:z=-?\d{1,3}(.\d{1,2})?;$'
like image 350
kyo Avatar asked Feb 22 '23 08:02

kyo


1 Answers

Folks do this kind of thing sometimes

label_value = r'\w=-?\d{1,3}(\.\d{1,2})?'
line = r'^C:{0}:{0}:{0};$'.format( label_value )
line_pat= re.compile( line )

This is slightly smarter.

label_value = r'(\w)=(-?\d{1,3}(?:\.\d{1,2})?)'
line = r'^C:{0}:{0}:{0};$'.format( label_value )
line_pat= re.compile( line )

Why? It collects the label and the entire floating-point value, not just the digits to the right of the decimal point.

In the unlikely case that order of labels actually does matter.

value = r'(-?\d{1,3}(?:\.\d{1,2})?)'
line = r'^C:x={0}:y={0}:z={0};$'.format( value )
line_pat= re.compile( line )

This requires the three labels in the given order. One of those things that's likely to change.

like image 114
S.Lott Avatar answered Feb 23 '23 20:02

S.Lott