Python reuse

I need to match the text.

Ej:

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

If the values ​​after x, y or z take values ​​corresponding to:

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

How can I reuse this?

These are the only values ​​that are variables. All other characters must be corrected. I mean, they should be in that exact order.

Is there 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})?;$' 
+4
source share
3 answers

People sometimes do things like this.

 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 a little 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 all floating point values, not just the digits to the right of the decimal point.

In the unlikely event that the order of the labels actually matters .

 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 three labels in this order. One of those things that can change.

+8
source

Since the regex that I selected had an error that I deleted.

However, whenever I need to develop or test a new regular expression, I usually have a game with online tools that let you view the results of your regular expression in real time.

Although I am not specifically python, I usually use this

0
source

This will not return false negatives, but a small number of false positives:

 '^C(:[xyz]=-?\d{1,3}(.\d{1,2})?){3}' 

false positives are cases where x, y, and z occur in the wrong combinations (i.e., y: x: z, x: x: z, etc.).

0
source

Source: https://habr.com/ru/post/1398501/


All Articles