user11883684
user11883684

Reputation:

Python: how to choose only certain integers within brackets using regex

I am stuck while writing a function of searching integers in square brackets that should find from an input string all integers that are enclosed in brackets taking into account an additional restriction: there can be whitespace between the number and the brackets, but no other character besides those that make up the integer.

So far, I wrote the code below, but it doesn't work for the last test with +-43 which shouldn't be count as an integer. Could you help me to solve this issue?

Thanks!

import re

def integers_in_brackets(s):
    l = list(int(s) for s in re.findall(r'\[\s*\+?(-?\d+)\s*\]', s))
    print(l)
    return list(l)

Tests:

integers_in_brackets("  afd [asd] [12 ] [a34]  [ -43 ]tt [+12]xxx")
integers_in_brackets("afd [asd] [12 ] [a34]  [         -43 ]tt [+12]xxx!")
integers_in_brackets("afd [128+] [47 ] [a34]  [ +-43 ]tt [+12]xxx!")

Upvotes: 1

Views: 95

Answers (1)

tripleee
tripleee

Reputation: 189457

Your regular expression quite literally says optional plus followed by optional minus. If that's not what you want, perhaps you want either a plus or a minus?

r'\[\s*([-+]?\d+)\s*\]'

If you want either but not both, but capture a minus but not a plus, maybe add a lookahead to say "optional plus if not immediately followed by a minus":

r'\[\s*(?:\+(?!-))?(-?\d+)\s*\]'

Upvotes: 1

Related Questions