Regular expression for printing integers within brackets

前端 未结 3 1530
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 18:35

First time ever using regular expressions and can\'t get it working although there\'s quite a few examples in stackoverflow already.

How can I extract integers which are

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-21 19:27

    If you need to fail the match in [ +-34 ] (i.e. if you needn't extract a negative number if there is a + before it) you will need to use

    \[\s*(?:\+|(-))?(\d+)\s*]
    

    and when getting a match, concat the Group 1 and Group 2 values. See this regex demo.

    Details

    • \[ - a [ char
    • \s* - 0+ whitespaces
    • \+? - an optional + char
    • (-?\d+) - Capturing group 1 (the actual output of re.findall): an optional - and 1+ digits
    • \s* - 0+ whitespaces
    • ] - a ] char.

    In Python,

    import re
    text = "dijdi[d43]     d5[55++][ 43]  [+32]dm dij [    -99]x"
    numbers_text = [f"{x}{y}" for x, y in re.findall(r'\[\s*(?:\+|(-))?(\d+)\s*]', text)]
    numbers = list(map(int, numbers_text))
    
    # => [43, 32, -99] for both
    

提交回复
热议问题