使用 Python 提取字符串中字符前的数字 [英] Extract Number before a Character in a String Using Python
问题描述
我试图在一系列字符串中提取字符M"之前的数字.字符串可能如下所示:
I'm trying to extract the number before character "M" in a series of strings. The strings may look like:
"107S33M15H"
"33M100S"
"12M100H33M"
所以基本上会有一组由不同字符分隔的数字,并且M"可能会出现不止一次.对于此处的示例,我希望我的代码返回:
so basically there would be a sets of numbers separated by different characters, and "M" may show up more than once. For the example here, I would like my code to return:
33
33
12,33 #doesn't matter what deliminator to use here
我能想到的一种方法是用M"分割字符串,并找到纯数字的项目,但我怀疑有更好的方法来做到这一点.非常感谢您的帮助.
One way I could think of is to split the string by "M", and find items that are pure numbers, but I suspect there are better ways to do it. Thanks a lot for the help.
推荐答案
您可以使用简单的 (\d+)M
正则表达式(1+ digit(s) 后跟 M
使用 re.findall
将数字捕获到捕获组中.
You may use a simple (\d+)M
regex (1+ digit(s) followed with M
where the digits are captured into a capture group) with re.findall
.
参见 IDEONE 演示:
import re
s = "107S33M15H\n33M100S\n12M100H33M"
print(re.findall(r"(\d+)M", s))
这是一个正则表达式演示
这篇关于使用 Python 提取字符串中字符前的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!