简体   繁体   English

使用Python中的正则表达式从字符串中提取数字(包括破折号)

[英]Extract number (dash included) from string using regex in Python

Hello and thanks for helping.您好,感谢您的帮助。

String examples:字符串示例:

"Hello 43543" ---> "43543" “你好 43543” ---> “43543”
"John Doe 434-234" ---> "434-234" “约翰·多伊 434-234”--->“434-234”

I need a regex to extract the examples on the right.我需要一个正则表达式来提取右边的例子。

If all your strings are like this, you can achieve the same without re :如果您的所有字符串都是这样,则无需re即可实现相同的效果:

s = "John Doe 434-234"
n = s.split()[-1] 

print(n)

>>> "434-234"

It will split your string on spaces and give you the last field.它将在空格上拆分您的字符串并为您提供最后一个字段。

I would do it following way:我会这样做:

import re
pattern = r'\d[0-9\-]*'
number1 = re.findall(pattern,'Hello 43543')
number2 = re.findall(pattern,'John Doe 434-234')
print(number1[0]) #43543
print(number2[0]) #434-234

My solution assumes that you are looking for any string starting with digit and with all other characters being digit or - , this mean it will also grab for example 4--- or 9-2-4--- and so on, however this might be not issue in your use case.我的解决方案假设您正在寻找任何以 digit 开头的字符串,并且所有其他字符都是 digit 或- ,这意味着它也会抓取例如4---9-2-4---等等,但是这个在您的用例中可能不是问题。

I want to note that before writing pattern, you should answer question: what it should match exactly ?我想指出,编写模式之前,您应该回答问题:它应该完全匹配什么 My pattern works as intended for examples you given, but keep in mind that this do NOT automatically mean it would give desired output with all data you might want to process using it.我的模式按您给出的示例的预期工作,但请记住,这并不自动意味着它会为您可能想要使用它处理的所有数据提供所需的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM