[英]How can I extract number and dots from a string using regex in python?
I am trying to extract number and dots from a string in python3 but with no success.我正在尝试从 python3 中的字符串中提取数字和点,但没有成功。 Actually I tried using the regex search function but I get only the first number and not dots and the following number.实际上我尝试使用正则表达式搜索 function 但我只得到第一个数字而不是点和后面的数字。 Here's an example of my test这是我的测试示例
string = "CDS complement(129..1049)"
print(int(re.search(r'\d+', string).group()))
129
But actually I would like to get:但实际上我想得到:
129..1049
I tried also to improve my code with:我还尝试通过以下方式改进我的代码:
print(int(re.search(r'\d+\.\.\d+', line).group()))
but I get this error:但我收到此错误:
ValueError: invalid literal for int() with base 10: '129..1049'
Can you help me?你能帮助我吗?
Thanks in advance.提前致谢。
Your regex works fine.您的正则表达式工作正常。 re.search(r'\d+\.\.\d+', line)
returns '129..1049'
, and so when you try to pass that string to int()
, it fails. re.search(r'\d+\.\.\d+', line)
返回'129..1049'
,因此当您尝试将该字符串传递给int()
时,它会失败。 You'll have to manually split
the string into its two integer parts first.您必须首先手动将字符串split
为两个 integer 部分。
You can use re to get all the numbers:您可以使用 re 获取所有数字:
import re
str1 = "CDS complement(129..1049)"
print(re.findall('\d+', str1))
I am not sure how to get the dots tho我不知道如何得到这些点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.