Write a Regex to extract number before '/'

前端 未结 5 611
情话喂你
情话喂你 2021-01-29 06:08

I don\'t want to use string split because I have numbers 1-99, and a column of string that contain \'#/#\' somewhere in the text.

How can I write a regex to extract the

5条回答
  •  梦谈多话
    2021-01-29 07:02

    You can still use str.split() if you carefully construct logic around it:

    t = "He got 10/19 questions right."
    t2 = "He/she got 10/19 questions right"
    
    
    for q in [t,t2]:
    
    
        # split whole string at spaces
        # split each part at / 
        # only keep parts that contain / but not at 1st position and only consists
        # out of numbers elsewise
        numbers = [x.split("/") for x in q.split() 
                   if "/" in x and all(c in "0123456789/" for c in x)
                  and not x.startswith("/")]
        if numbers:
            print(numbers[0][0])
    

    Output:

    10
    10
    

提交回复
热议问题