代码之家  ›  专栏  ›  技术社区  ›  Khalil Al Hooti

提取文本右侧的数字

  •  -4
  • Khalil Al Hooti  · 技术社区  · 7 年前

    假设python中有一些字符串以数字结尾。

    2te2xt12
    text1
    text143
    te2xt341
    

    如何获得最正确的数字序列:

    2te2xt12  >>  12
    text1     >>  1
    text143   >>  143
    te2xt341  >>  341
    

    有一种简单易行的方法吗。

    我对re一无所知

    提前谢谢

    4 回复  |  直到 7 年前
        1
  •  5
  •   frankegoesdown    7 年前
    import re
    s=r"""1231ololo767980716"""
    re.match('.*?([0-9]+)$', s).group(1)
    
    >>> '767980716'
    

    next(re.finditer(r'\d+$', s)).group(0)
    >>> '767980716'
    

    regexp组件的说明:

    • .*? 是一种非贪婪匹配,只消耗尽可能多的能量(a 贪婪匹配将消耗除最后一个数字以外的所有内容)。

    • [0-9] \d à­ª ൨

    • 括号(())使表达式的内容成为一个组,可以使用组(1)检索该组(或第二个组为2,整个匹配为0)。
    • + 表示多个条目(末尾至少有一个数字)。
    • $ 仅匹配输入的结尾。

    以及您可以在此处找到的所有组件: https://www.rexegg.com/regex-quickstart.html 非常有用的备忘单

        2
  •  3
  •   Pushpesh Kumar Rajwanshi    7 年前

    \d+$ 你应该得到你想要的东西,

    import re
    
    arr = ['2te2xt12',
    'text1',
    'text143',
    'te2xt341']
    
    for s in arr:
     m = re.search(r'\d+$', s)
     if (m):
      print(s + ' >> ' + m.group())
    

    印刷品,

    2te2xt12 >> 12
    text1 >> 1
    text143 >> 143
    te2xt341 >> 341
    
        3
  •  2
  •   Kanchana Ranasinghe    7 年前

    试试这个?功能测试应该满足您的需要。

    import re
    
    def test(string):
        m = re.search(r'\d+$', string)
        if m is not None:
            print(m.group())
    
        4
  •  2
  •   paradocslover    5 年前

    re.findall('\d+$',yourString)[0]
    

    要了解有关正则表达式的更多信息,请参阅文档 here