Reputation: 63
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})?;$'
Upvotes: 4
Views: 656
Reputation: 1646
Since the regex I put up had a bug I have removed it.
However whenever I need to develop or test a new regex i generally have a play with online tools that allow you to view the results of your regex in real time.
While not specifically python I generally use this one
Upvotes: 0
Reputation: 391952
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.
Upvotes: 8
Reputation: 17525
This will return no false negatives, but a small number of false positives:
'^C(:[xyz]=-?\d{1,3}(.\d{1,2})?){3}'
The false positives are the cases where x, y, and z occur in the wrong combinations (i.e. y:x:z, x:x:z, etc.).
Upvotes: 0