Home > front end >  how to remove special characterics in regex python
how to remove special characterics in regex python

Time:08-06

I have the following string:"afd [128 ] [47 ] [a34] [ -43 ]tt [ 12]xxx!"

I wish to remove all characters except numbers 47 and 12. I have tried with several different regex combinations for hours but I just cant figure it out.

import re

def integers_in_brackets(s):
res =[]
res = re.findall(r'[ -]?\b\d \b',s)

print(res)

for i in range(0, len(res)):
    res[i] = int(res[i])

return res

the function should return [47, 12]

CodePudding user response:

The following regex should match your requirements

(?<=[\[\s\ ])\b\d \b(?=[\]\s])

CodePudding user response:

What about this regex:

"\[(?P<value>\s*\ ?\d \s*)\]"g

Regex 101

Explanation:

  • allows patterns like [ 22 ], [ 22 ], [ 22], [22]
  • rejects patterns like [ 22 ], [ -22], [-22], [22 ]

Python

import re

test_str = "afd [128 ] [47 ] [a34]  [  -43 ]tt [12]xxx [  2222]cxx  [ - 12 ]yy [1 2]xxx!"

arr = re.findall("\[(?P<value>\s*\ ?\d \s*)\]", test_str)
print(arr)
  • Related