Andreas Geo Andreas Geo - 6 months ago 46
C++ Question

Regular expression for parsing array indexing expressions in C++

Am doing some semantic analysis on C++ source code.
I have a regular expression to transform the array declarations from

int [123] [1234]
int [number] [number]

But I want the expression also be able to match dimensions such as these
int [i * x][ring_size][w + 6]

How do I tell it to match anything inside (symbols and spaces included) [ ]?

My regular expression so fas is:
regex arrayDims("\\[[0-9]+\\]");
. I am using C++11 regex header.

Thank you


If you want to match anything inside [], then try using \\[.+?\\], or something similar. The ? turns the * into non-greedy. Read more on this page.

Edit: I have to note that, while this works for slightly more complex expression than just numbers, if there are more [] inside the expression, this will not work.

E.g. applying my pattern to array[anotherarray[5]] results in [anotherarray[5], instead of [anotherarray[5]] (note the extra bracket at the end).

See this answer for more information on bracket matching.