简体   繁体   中英

Regex to return integers in square brackets in a string

So I'm finding difficulty in applying regex. Need to create a function which will return a list of integers enclosed in brackets in the string. There can be whitespace between the number and brackets but no other character.

So basically calling the function:

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

Should give:

[12, -43, 12]

Also, there is no '+' sign in the integers with '+' in the list.

I have already tried this but to no good:

re.findall(r'[-]?\\d+', " afd [asd] [12 ] [a34] [ -43 ]tt [+12]xxx")

This one returns:

['12', '34', '-43', '12']

Try this: https://repl.it/repls/SizzlingTornUtility

It uses this regex \\[\\s*([-+]?\\d+)\\s*\\]

import re
def integers_in_brackets(string):
  answers = [int(a) for a in re.findall(r'\[\s*([-+]?\d+)\s*\]', string)]

  return answers
print(integers_in_brackets("  afd [asd] [12 ] [a34]  [ -43 ]tt [+12]xxx"))

returns

[12, -43, 12]

Might be overkill, but it works:

text = "  afd [asd] [12 ] [a34]  [ -43 ]tt [+12]xxx"
[''.join(re.findall(r'[-]?\d+', _)) for _ in re.findall(r'\[\s?[+]?[-]?\d+\s?\]', text)]

Here with a good regex and using map to convert the items of the list to integers.

import re

txt = "  afd [asd] [12 ] [a34]  [ -43 ]tt [+12]xxx"
rgx = "\[\s*\+?(-?\d+)\s*\]"
res = list(map(int, re.findall(rgx, txt)))
print(res)

Gives:

[12, -43, 12]

The following appears to do what you want:

>>> text = "  afd [asd] [12 ] [a34]  [ -43 ]tt [+12]xxx"
>>> pattern = r'\[\s*([-+]?\d+)\s*\]'
>>> [int(x) for x in re.findall(pattern, text)]
[12, -43, 12]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM