0

I'm trying to isolate array name and array size from code. This example of expected input:

blah_blah[blahvar]
blah_ha[2]
blah_[]

I need to match names (blah_blah, blah_ha, blah_) and text inside brackets (blahvar, 2, ''). I have this regex:

([a-zA-z_]+)(\[[a-zA-Z_]*\])

But it's not working. Please help.

2
  • "It's not working" is never a good enough description of the problem. What's wrong? Does it match too much? Too little? Does it match the right things but you're having trouble extracting the groups? Commented Jul 2, 2012 at 6:00
  • 1
    This is probably not the cause of your problem, but first part of the regex ([a-zA-z_]+) has lowercase 'z' instead of uppercase 'Z' Commented Jul 2, 2012 at 6:08

2 Answers 2

3

Use This regular expression

([\w]+)\[([\w]*)\]

Group 1 will match the array name and Group 2 will match the index

Sign up to request clarification or add additional context in comments.

Comments

2

You need to include numbers:

([a-zA-z_0-9]+)(\[[a-zA-Z_0-9]*\])

Without that, your second example blah_ha[2] won't catch (the others do).

A shorter version (that captures every word character (letters, digits, etc.):

(\w+)(\[\w*\])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.