Python regular expression not matching

前端 未结 3 1596
攒了一身酷
攒了一身酷 2020-11-30 15:03

This is one of those things where I\'m sure I\'m missing something simple, but... In the sample program below, I\'m trying to use Python\'s RE library to parse the string \"

相关标签:
3条回答
  • 2020-11-30 15:32

    You should use re.findall instead:

    >>> line = '    0 repaired, 90.31% done'
    >>> 
    >>> pattern = re.compile("\d+[.]\d+(?=%)")
    >>> re.findall(pattern, line)
    ['90.31']
    

    re.match will match at the start of the string. So you would need to build the regex for complete string.

    0 讨论(0)
  • 2020-11-30 15:38

    try this if you really want to use match:

    re.match(r'.*(\d+\.\d+)% done$', line)
    

    r'...' is a "raw" string ignoring some escape sequences, which is a good practice to use with regexp in python. – kratenko (see comment below)

    0 讨论(0)
  • 2020-11-30 15:40

    match only matches from the beginning of the string. Your code works fine if you do pct_re.search(line) instead.

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