代码之家  ›  专栏  ›  技术社区  ›  Liam

如何使用正则表达式提取字符前后的数字?例如5x5或12x5-python[关闭]

  •  -1
  • Liam  · 技术社区  · 6 年前

    因此,如果我输入一个字符串值,如“3x3”或“12x10”-我希望能够将第一个和第二个数字提取为整数。

    例如,如果我输入3x3,则下限为3,上限为3。或者如果我输入10x3,则下限为10,上限为3。

    最干净的方法是什么?

    我知道我可以使用int(string[index])访问和转换字符串中的字符,但是我如何处理输入的任何字符串?

    干杯

    5 回复  |  直到 6 年前
        1
  •  2
  •   Sheldore    6 年前

    你可以使用 x 作为分隔符来拆分字符串,然后将字符串映射到类型 int

    number = "12x10"
    lower, upper = list(map(int, number.split('x')))
    # 12, 10
    
    number = "3x3"
    lower, upper = list(map(int, number.split('x')))
    # 3, 3
    
        2
  •  2
  •   Mohammad Banisaeid    6 年前

    使用正则表达式:

    import re
    
    text = '13x666'
    match = re.match('(\d+)x(\d+)', text)
    if match:
        print(match.group(1), match.group(2))
    

    \d 匹配数字和 \d+ 表示一个或多个数字。

        3
  •  0
  •   r1024    6 年前

    你可以尝试在每 x 在字符串中。或者像上面提到的其他答案一样使用正则表达式。

    expression = "12x10x20x45x50x45"
    numbers = expression.split('x')
    print(numbers)
    

    实例输出
    ['12', '10', '20', '45', '50', '50']

        4
  •  0
  •   ApprenticeHacker    6 年前

    也许是一条干净的路

    t = number.split('x')
    x, y = int(t[0]), int(t[2])
    
        5
  •  0
  •   Phx Dev    6 年前

    这样尝试:

    import re
    
    string = "10x3" 
    regexp = r"(\d+)x(\d+)"
    regexmatch = re.match(regexp, string)
    
    if regexmatch is not None:
        print("TRUE")
        print(re.search(regexp, string).groups())
        lower = regexmatch.group(1)
        upper = regexmatch.group(2)
        print("LOWER : " + str(lower))
        print("UPPER : " + str(upper))
    else:
        print("FALSE")