Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java to find substring of a bigger string using Regular Expression

Tags:

java

string

regex

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 
like image 201
digiarnie Avatar asked Mar 01 '09 22:03

digiarnie


People also ask

How do I find a particular substring in a string in Java?

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.

How do you trim a string after a specific character in Java?

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.

What is the difference between matches () and find () in Java RegEx?

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.


1 Answers

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" } 
like image 181
Bryan Kyle Avatar answered Sep 17 '22 23:09

Bryan Kyle