Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
918 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
33M100S
12M100H33M"
print(re.findall(r"(d+)M", s))

And here is a regex demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...