简体   繁体   English

如何在 python 中使用正则表达式从字符串中提取数字和点?

[英]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.

相关问题 我想从 python 3 中的字符串中提取所有十进制数,如何在不使用正则表达式的情况下做到这一点? - I want to extract all decimal numbers from a string in python 3, how can I do that without using regex? 如何使用正则表达式从冒号前的字符串中提取单词并在 python 中排除 \n - How can i extract words from a string before colon and excluding \n from them in python using regex 蟒蛇; 通过正则表达式使用字符串中的点解析版本号 - Python; parse version number with dots from string via regex 使用Python Regex从字符串中提取门牌号和街道名称 - Extract House Number and Street Name from string using Python Regex 如何使用 selenium 从字符串中提取数字? - How can I extract a number from a string using selenium? 使用Python中的正则表达式从字符串中提取数字(包括破折号) - Extract number (dash included) from string using regex in Python 如何使用Python正则表达式从字符串中提取未知数量的不同部分? - How to extract unknown number of different parts from string with Python regex? 如何使用正则表达式从字符串中提取特定类型的数字? - How to extract a specific type of number from a string using regex? 如何使用Python从串联字符串中提取名称? - How can I extract names from a concatenated string using Python? 如何在Python中使用正则表达式提取字符串? - How can I use regex in Python to extract the string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM