在字符串中的子字符串后查找数字

Rob*_*988 -1 python regex string python-2.7 python-3.x

想要拥有可以在字符串中的子字符串之后找到数字的函数,例如:

>>> find_number('abc123de34','e')
34
>>> find_number('abc123de34','de')
34
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?

Srd*_* M. 8

正则表达式char(\d+)

细节:

  • \d匹配一个数字(等于[0-9]
  • + 一次和无限次之间的匹配
  • () 拍摄组

蟒蛇代码

字符串格式化语法"%s" % var%s令牌允许插入(并可能格式化)一个字符串。

def find_number(text, c):
    return re.findall(r'%s(\d+)' % c, text)

find_number('abce123de34', 'e') >> ['123', '34']
find_number('abce123de34', 'de') >> ['34']
Run Code Online (Sandbox Code Playgroud)