How to extract a substring using regex
Assuming you want the part between single quotes, use this regular expression with a Matcher
:
"'(.*?)'"
Example:
String mydata = "some string with 'the data i want' inside";Pattern pattern = Pattern.compile("'(.*?)'");Matcher matcher = pattern.matcher(mydata);if (matcher.find()){ System.out.println(matcher.group(1));}
Result:
the data i want
You don't need regex for this.
Add apache commons lang to your project (http://commons.apache.org/proper/commons-lang/), then use:
String dataYouWant = StringUtils.substringBetween(mydata, "'");
import java.util.regex.Matcher;import java.util.regex.Pattern;public class Test { public static void main(String[] args) { Pattern pattern = Pattern.compile(".*'([^']*)'.*"); String mydata = "some string with 'the data i want' inside"; Matcher matcher = pattern.matcher(mydata); if(matcher.matches()) { System.out.println(matcher.group(1)); } }}