Python Regular Expression example

前端 未结 9 1489
天命终不由人
天命终不由人 2020-12-08 10:04

I want to write a simple regular expression in Python that extracts a number from HTML. The HTML sample is as follows:

Your number is 123
         


        
相关标签:
9条回答
  • 2020-12-08 10:14
    import re
    found = re.search("your number is <b>(\d+)</b>", "something.... Your number is <b>123</b> something...")
    
    if found:
        print found.group()[0]
    

    Here (\d+) is the grouping, since there is only one group [0] is used. When there are several groupings [grouping index] should be used.

    0 讨论(0)
  • 2020-12-08 10:21
    import re
    m = re.search("Your number is <b>(\d+)</b>",
          "xxx Your number is <b>123</b>  fdjsk")
    if m:
        print m.groups()[0]
    
    0 讨论(0)
  • 2020-12-08 10:22
    import re
    x = 'Your number is <b>123</b>'
    re.search('(?<=Your number is )<b>(\d+)</b>',x).group(0)
    

    this searches for the number that follows the 'Your number is' string

    0 讨论(0)
  • 2020-12-08 10:22
    import re
    print re.search(r'(\d+)', 'Your number is <b>123</b>').group(0)
    
    0 讨论(0)
  • 2020-12-08 10:24

    To extract as python list you can use findall

    >>> import re
    >>> string = 'Your number is <b>123</b>'
    >>> pattern = '\d+'
    >>> re.findall(pattern,string)
    ['123']
    >>>
    
    0 讨论(0)
  • 2020-12-08 10:27

    You can use the following example to solve your problem:

    import re
    
    search = re.search(r"\d+",text).group(0) #returns the number that is matched in the text
    
    print("Starting Index Of Digit", search.start())
    
    print("Ending Index Of Digit:", search.end())
    
    0 讨论(0)
提交回复
热议问题