Regex for getting all digits in a string after a character

前端 未结 2 1582
花落未央
花落未央 2021-01-20 00:38

I am trying to parse the following string and return all digits after the last square bracket:

C9: Title of object (foo, bar) [ch1, CH12,c03,4]
2条回答
  •  一生所求
    2021-01-20 01:25

    You can rather find all digits in the substring after the last [ bracket:

    >>> s = 'C9: Title of object (fo[ 123o, bar) [ch1, CH12,c03,4]'
    >>> # Get substring after the last '['.
    >>> target_string = s.rsplit('[', 1)[1]
    >>>
    >>> re.findall(r'\d+', target_string)
    ['1', '12', '03', '4']
    

    If you can't use split, then this one would work with look-ahead assertion:

    >>> s = 'C9: Title of object (fo[ 123o, bar) [ch1, CH12,c03,4]'
    >>> re.findall(r'\d+(?=[^[]+$)', s)
    ['1', '12', '03', '4']
    

    This finds all digits, which are followed by only non-[ characters till the end.

提交回复
热议问题