If I have a string like this:
FOO[BAR]
I need a generic way to get the "BAR" string out of the string so that no matter what string is between the square brackets it would be able to get the string.
e.g.
FOO[DOG] = DOG
FOO[CAT] = CAT
If I have a string like this:
FOO[BAR]
I need a generic way to get the "BAR" string out of the string so that no matter what string is between the square brackets it would be able to get the string.
e.g.
FOO[DOG] = DOG
FOO[CAT] = CAT
the non-regex way:
alternatively, for slightly better performance/memory usage (thanks Hosam):
I think your regular expression would look like:
Assuming that FOO going to be constant.
So, to put this in Java:
This will return the value between first '[' and last ']'
Foo[Bar] => Bar
Foo[Bar[test]] => Bar[test]
Note: You should add error checking if the input string is not well formed.
This is a working example :
RegexpExample.java
It displays :
I'd define that I want a maximum number of non-] characters between
[
and]
. These need to be escaped with backslashes (and in Java, these need to be escaped again), and the definition of non-] is a character class, thus inside[
and]
(i.e.[^\\]]
). The result:You should be able to use non-greedy quantifiers, specifically *?. You're going to probably want the following:
This will give you a pattern that will match your string and put the text within the square brackets in the first group. Have a look at the Pattern API Documentation for more information.
To extract the string, you could use something like the following: