4

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})?;$'

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think I'd move the \w= out of label_value since he said he wanted x, y and z in that exact order. Otherwise, great.
@TimPietzcker: It's a tough call. When someone says "exactly that order", I hear "typically that order". I've never seen that kind of thing remain fixed for long. However, this may be an exception; it's possible that out-of-order is actually a reason to treat the data as invalid.
0

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.).

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.