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
To locate a substring in a string, use the indexOf() method. Let's say the following is our string. String str = "testdemo"; Find a substring 'demo' in a string and get the index.
Java String trim() The Java String class trim() method eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in Java string checks this Unicode value before and after the string, if it exists then the method removes the spaces and returns the omitted string.
Difference between matches() and find() in Java RegexThe matches() method returns true If the regular expression matches the whole text. If not, the matches() method returns false. Whereas find() search for the occurrence of the regular expression passes to Pattern.
You should be able to use non-greedy quantifiers, specifically *?. You're going to probably want the following:
Pattern MY_PATTERN = Pattern.compile("\\[(.*?)\\]");
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:
Matcher m = MY_PATTERN.matcher("FOO[BAR]"); while (m.find()) { String s = m.group(1); // s now contains "BAR" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With