检查指定的数字填充

时间:2016-09-13 19:48:53

标签: python maya

我正在尝试检查我的场景中的项目列表,看看它们是否在其名称的末尾带有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'\1', item)
    print mo

然后它返回01005作为输出,我希望它只返回005 ..我怎么要它检查它是否包含3个填充?此外,是否可以在支票中加入下划线?这是最好的方式吗?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

for item in eg_list:
    if re.match(".*_\d{3}$", item):
        print item.split('_')[-1]

匹配以下结尾的任何内容: _和下划线,\d一个数字,{3}三个,$行的结尾。

Regular expression visualization

Debuggex Demo

打印该项目,我们将其拆分为_下划线并取最后一个值,索引为[-1]

.*?([0-9]*)$不起作用的原因是因为[0-9]*匹配0次或更多次,所以它不能匹配。这意味着它也将匹配.*?$,它将匹配任何字符串。

请参阅regex101.com

上的示例

答案 2 :(得分:1)

[0-9]规范后的星号表示您期望任意随机出现的数字0-9。从技术上讲,这个表达式也匹配test_charlie_rig。你可以在这里测试http://pythex.org/

用{3}替换星号表示您想要3个数字。

^.+_(\d{3})$

如果您知道您的格式将接近您展示的示例,那么您可以更加明确地使用正则表达式模式来防止更多意外匹配

int[] myArray = new int[10];
// initialize myArray with values...
Arrays.sort(myArray, new Comparator<Integer>() {
    public int compare(Integer o1, Integer o2) {
        // if o1 is zero, then return a 'less' than value (-1). 
        // otherwise, return an 'equivalent' value (0)
        return o1 == 0 ? -1 : 0;
    }           
});

答案 3 :(得分:1)

除非需要,我通常不喜欢正则表达式。这应该有效并且更具可读性。

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