I am not a dab at regulars but I have a task at hand and I think expressions might be handy. I want to check if a string like 'stringList[0]', 'stringList[2]' fits the pattern, that is I am trying to figure out whether a string is a textual representation of a collection's element. What would that pattern look like? I will use java as a primary tool. Thank you so much in advance.
2 Answers
To match for 'stringList[0]' you can use
"stringList\\[\\d+\\]"
which matches stringList, followed by [ and the at least one digit followed by ]
Edit:
To match what was clarified
"[\\p{L}_$][\\p{L}\\p{N}_$]*\\[\\d+\\]"
which I think matches any valid identifier. Starting with with any letter, _ or $ and then followed by one or more letter, number, _ or $ followed by [, then 1 or more digits and then another ].
1 Comment
"stringList\\[(\\d+)\\]"
would match "stringList[a number]"
"([a-zA-Z]+)\\[(\\d+)\\]"
would match any sequence of upper/lowercase characters followed by "[a number]" legal java class/field names may contain numbers (not as a first character) and underscores as well (and maybe more things i cant think of?), so you'd need something more complex for the 1st block, but you could probbaly google for a "full" expression for legal java class/field names