Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
942 views
in Technique[技术] by (71.8m points)

regex - Extract Number before a Character in a String Using Python

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...