[英]Python RegEx check string
im trying to set correct version on output.我试图在 output 上设置正确的版本。 I have this possible strings:我有这个可能的字符串:
and i need to check, if the "0."我需要检查,如果“0”。 is on the start (to set output without 0. or 0.0.)正在开始(设置 output 不带 0. 或 0.0.)
Output 1. will have just "4.1" , 2. gonna stay the same and 3. will be 1.4.1 Output 1. 将只有"4.1" , 2. 保持不变3. 将是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.我试图设置正确的表达式,如^([0\.]{1})([.\d]{3})+$
但即使我使用 {1} 量词(只有一个“0”)它也没有正常工作。
Anyone with some clue?有人有线索吗?
If there should be 4 digit parts with 3 dots, you can first assert the format using a positive lookahead.如果应该有 3 个点的 4 位数字部分,您可以首先使用正向超前断言格式。
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 dots (?=\d+(?:\.\d+){3}$)
正向前瞻,用 3 个点断言 4 位数字部分0+\.
match 1+ zeroes and .
匹配 1+ 个零和.
(?:0+\.)*
Optionally repeat matching 1+ zeroes and .
(?:0+\.)*
可选择重复匹配 1+ 个零和.
Regex demo |正则表达式演示| Python demo Python 演示
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 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]*
You can use您可以使用
import re
texts = ['0.0.4.1','7.51.4.1','0.1.4.1']
for text in texts:
m = re.fullmatch(r'(?:0+\.)*(\d+(?:\.\d+)*)', text)
if m:
print(m.group(1))
# => 4.1
# 7.51.4.1
# 1.4.1
See the Python demo .请参阅Python 演示。 NOTE : re.fullmatch
requires the full string match, so no need specifying the ^
and $
anchors.注意: re.fullmatch
需要完整的字符串匹配,因此无需指定^
和$
锚点。
NOTE 2 : If you do not want to match anything in 0.0.0.0
add the if m.group(1).replace('0',''):
check before returning the value, see this Python demo .注意 2 :如果您不想匹配0.0.0.0
中的任何内容,请添加if m.group(1).replace('0',''):
在返回值之前检查,请参阅此 Python 演示。
See the regex demo meaning查看正则表达式演示的含义
(?:0+\.)*
- zero or more occurrences of one or more 0
s and a dot (?:0+\.)*
- 一个或多个0
和一个点的零次或多次出现(\d+(?:\.\d+)*)
- Group 1: one or more digits and then zero or more repetitions of a dot and one or more digits. (\d+(?:\.\d+)*)
- 第 1 组:一位或多位数字,然后是一个点和一位或多位数字的零次或多次重复。Use this simple regex: ^[0\.]+
使用这个简单的正则表达式: ^[0\.]+
https://regex101.com/r/zUKutI/1/ https://regex101.com/r/zUKutI/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.