I'm trying to extract the number before character "M" in a series of strings. The strings may look like:
"107S33M15H"
"33M100S"
"12M100H33M"
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
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.
This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.
Getting a substring of a string is extracting a part of a string from a string object. It is also called a Slicing operation. You can get substring of a string in python using the str[0:n] option.
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
.
See IDEONE demo:
import re
s = "107S33M15H\n33M100S\n12M100H33M"
print(re.findall(r"(\d+)M", s))
And here is a regex demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With