Extract Number before a Character in a String Using Python

前端 未结 2 1874
梦如初夏
梦如初夏 2020-12-11 07:35

I\'m trying to extract the number before character \"M\" in a series of strings. The strings may look like:

\"107S33M15H\"
\"33M100S\"
\"12M100H33M\"
         


        
相关标签:
2条回答
  • 2020-12-11 08:02

    You can use rpartition to achieve that job.

    s = '107S33M15H'    
    prefix = s.rpartition('M')[0]
    
    0 讨论(0)
  • 2020-12-11 08:26

    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

    0 讨论(0)
提交回复
热议问题