user2030113
user2030113

Reputation: 485

Get string inside brackets

I want to fetch the string inside the square bracket, which is given as array

u16 arrayName_1[8][7]

I have python code which can find the 1-Dimensional array and get the character inside squre brackets.

var = 'u16 arrayName_1[8]'
index = re.split('\[(.*?)\]', str(var))

index[0] will give 'u16 arrayName_1'.

index[1] will give '8'.

Problem: I want to get string inside brackets of 2D array. i tried below code but it is not desired result.

var = u16 arrayName_1[8][7]
index= re.split('(\[.*\])$', str(var))

index[0] will give 'u16 arrayName_1'.

index[1] will give '[8][7]'. This is wrong result.

I want output like:

index[1] = '8'

index[2] = '7'

Upvotes: 1

Views: 1797

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You may use your own pattern in re.findall to grab all the contents inside [...]:

import re
var = 'u16 arrayName_1[8][7]'
index = re.findall(r'\[(.*?)\]', var)
print(index) # => ['8', '7']

See Python demo

To only match digits inside, use \[([0-9]+)] regex. Also, you do not have to escape the ] symbol outside the character class, and you should consider using raw string literals to define your regex patterns to avoid confusion with unescaped backslashes.

Upvotes: 3

Related Questions