Java- Extract part of a string between two special characters

bryan picture bryan · Feb 10, 2011 · Viewed 89.7k times · Source

I have been trying to figure out how to extract a portion of a string between two special characters ' and " I've been looking into regex, but frankly I cannot understand it.
Example in Java code:

String str="21*90'89\""; 

I would like to pull out 89

In general I would just like to know how to extract part of a string between two specific characters please.

Also it would be nice to know how to extract part of the string from the beginning to a specific character like to get 21.

Answer

Mark Byers picture Mark Byers · Feb 10, 2011

Try this regular expression:

'(.*?)"

As a Java string literal you will have to write it as follows:

"'(.*?)\""

Here is a more complete example demonstrating how to use this regular expression with a Matcher:

Pattern pattern = Pattern.compile("'(.*?)\"");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
    System.out.println(matcher.group(1));
}

See it working online: ideone