im trying to set correct version on output. I have this possible strings:
- 0.0.4.1 # 1.
- 7.51.4.1 # 2.
- 0.1.4.1 # 3.
and i need to check, if the “0.” is on the start (to set output without 0. or 0.0.)
Output 1. will have just “4.1”, 2. gonna stay the same and 3. will be 1.4.1
Im trying to set correct expresion like ^([0.]{1})([.d]{3})+$
but even if i use {1} quantifier (to just one “0.”) it doesnt work correctly.
Anyone with some clue?
Advertisement
Answer
If there should be 4 digit parts with 3 dots, you can first assert the format using a positive lookahead.
In the replacement use an empty string.
^(?=d+(?:.d+){3}$)0+.(?:0+.)*
^
Start of string(?=d+(?:.d+){3}$)
Positive lookahead, assert 4 digit parts with 3 dots0+.
match 1+ zeroes and.
(?:0+.)*
Optionally repeat matching 1+ zeroes and.
Example
import re strings = ["0.0.4.1", "7.51.4.1", "0.1.4.1", "001", "0.1", ".0.1", "0.0.0.0", "0.1.2.3.4.5"] pattern = r"^(?=d+(?:.d+){3}$)0+.(?:0+.)*" for s in strings: print(re.sub(pattern, "", s))
Output
4.1 7.51.4.1 1.4.1 001 0.1 .0.1 0 0.1.2.3.4.5
Other options might be matching zeroes and a .
at the start, and then repeatedly zeroes and a dot.
^0+.(?:0+.)*
Or a broader pattern to match all leading dots and zeroes:
^0+.[.0]*