检查非常指定的数字填充
Check for very specified numbers padding
我正在尝试检查场景中的项目列表,看看它们的名称末尾是否带有 3 个(版本)填充 - 例如。 test_model_001
如果他们通过,则该项目将通过,而未通过条件的项目将受到特定功能的影响..
假设我的物品清单如下:
- test_model_01
- test_romeo_005
- test_charlie_rig
我尝试并使用了以下代码:
eg_list = ['test_model_01', 'test_romeo_005', 'test_charlie_rig']
for item in eg_list:
mo = re.sub('.*?([0-9]*)$',r'', item)
print mo
它 return 我 01
和 005
作为输出,我希望它 return 我只是 005
而已。 . 我如何要求它检查它是否包含 3 个填充?另外,是否可以在支票中包含下划线?这是最好的方法吗?
您可以使用 {3}
仅要求 3 个连续数字并在前面加上下划线:
eg_list = ['test_model_01', 'test_romeo_005', 'test_charlie_rig']
for item in eg_list:
match = re.search(r'_([0-9]{3})$', item)
if match:
print(match.group(1))
这只会打印 005
。
for item in eg_list:
if re.match(".*_\d{3}$", item):
print item.split('_')[-1]
这匹配以以下结尾的任何内容:
_
和下划线,\d
一个数字,{3}
三个,$
行尾。
打印项目,我们将其拆分为 _
下划线并取最后一个值,索引 [-1]
之所以.*?([0-9]*)$
不行,是因为[0-9]*
匹配了0次或多次,所以什么也匹配不到。这意味着它还将匹配 .*?$
,这将匹配任何字符串。
参见 regex101.com
上的示例
[0-9] 规范后的星号表示您期望数字 0-9 出现的任意随机次数。从技术上讲,此表达式也匹配 test_charlie_rig。你可以在这里测试 http://pythex.org/
用 {3} 替换星号表示您需要 3 位数字。
.*?([0-9]{3})$
如果您知道您的格式将接近您展示的示例,您可以更明确地使用正则表达式模式以防止更多的意外匹配
^.+_(\d{3})$
除非需要,否则我通常不喜欢正则表达式。这应该可以工作并且更具可读性。
def name_validator(name, padding_count=3):
number = name.split("_")[-1]
if number.isdigit() and number == number.zfill(padding_count):
return True
return False
name_validator("test_model_01") # Returns False
name_validator("test_romeo_005") # Returns True
name_validator("test_charlie_rig") # Returns False
我正在尝试检查场景中的项目列表,看看它们的名称末尾是否带有 3 个(版本)填充 - 例如。 test_model_001
如果他们通过,则该项目将通过,而未通过条件的项目将受到特定功能的影响..
假设我的物品清单如下:
- test_model_01
- test_romeo_005
- test_charlie_rig
我尝试并使用了以下代码:
eg_list = ['test_model_01', 'test_romeo_005', 'test_charlie_rig']
for item in eg_list:
mo = re.sub('.*?([0-9]*)$',r'', item)
print mo
它 return 我 01
和 005
作为输出,我希望它 return 我只是 005
而已。 . 我如何要求它检查它是否包含 3 个填充?另外,是否可以在支票中包含下划线?这是最好的方法吗?
您可以使用 {3}
仅要求 3 个连续数字并在前面加上下划线:
eg_list = ['test_model_01', 'test_romeo_005', 'test_charlie_rig']
for item in eg_list:
match = re.search(r'_([0-9]{3})$', item)
if match:
print(match.group(1))
这只会打印 005
。
for item in eg_list:
if re.match(".*_\d{3}$", item):
print item.split('_')[-1]
这匹配以以下结尾的任何内容:
_
和下划线,\d
一个数字,{3}
三个,$
行尾。
打印项目,我们将其拆分为 _
下划线并取最后一个值,索引 [-1]
之所以.*?([0-9]*)$
不行,是因为[0-9]*
匹配了0次或多次,所以什么也匹配不到。这意味着它还将匹配 .*?$
,这将匹配任何字符串。
参见 regex101.com
上的示例[0-9] 规范后的星号表示您期望数字 0-9 出现的任意随机次数。从技术上讲,此表达式也匹配 test_charlie_rig。你可以在这里测试 http://pythex.org/
用 {3} 替换星号表示您需要 3 位数字。
.*?([0-9]{3})$
如果您知道您的格式将接近您展示的示例,您可以更明确地使用正则表达式模式以防止更多的意外匹配
^.+_(\d{3})$
除非需要,否则我通常不喜欢正则表达式。这应该可以工作并且更具可读性。
def name_validator(name, padding_count=3):
number = name.split("_")[-1]
if number.isdigit() and number == number.zfill(padding_count):
return True
return False
name_validator("test_model_01") # Returns False
name_validator("test_romeo_005") # Returns True
name_validator("test_charlie_rig") # Returns False