python - 如何抓取字符串中间的数字? (Python)

标签 python regex

random string
this is 34 the string 3 that, i need 234
random string
random string
random string
random string

random string
this is 1 the string 34 that, i need 22
random string
random string
random string
random string

random string
this is 35 the string 55 that, i need 12
random string
random string
random string
random string

在一个字符串中有多行。其中一行重复但每次都有不同的数字。我想知道如何将数字存储在这些行中。数字将始终位于行中的相同位置,但可以是任意数量的数字。

编辑:随机字符串中也可以包含数字。

最佳答案

使用正则表达式:

>>> import re
>>> comp_re = re.compile('this is (\d+) the string (\d+) that, i need (\d+)')
>>> s = """random string
this is 34 the string 3 that, i need 234
random string
random string
random string
random string

random string
this is 1 the string 34 that, i need 22
random string
random string
random string
random string

random string
this is 35 the string 55 that, i need 12
random string
random string
random string
random string
"""
>>> comp_re.findall(s)
[('34', '3', '234'), ('1', '34', '22'), ('35', '55', '12')]

关于python - 如何抓取字符串中间的数字? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6390651/

相关文章:

python - 如何分别传播字符串列表?

Java正则表达式匹配两个连续的辅音

javascript - 输入值在任意位置包含特定字符

javascript - 如何使用正则表达式将字符串替换为自身?

c++ - Boost 正则表达式抛出复杂性异常,而 std::regex 则不会

javascript - 从字符串末尾获取数字的最佳方法是什么?

python - 制作具有精确长度的 sin 'arc'

python - 将相同的函数与不同的参数组合起来 - Python

python - 如何创建一个 WTF 表单和 Flask 在计算后返回一个值?

python - 使用 PyEphem 将地心坐标(方位角、高程)转换为赤道坐标(RA、Dec)