Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a substring using regex

I have a string that has two single quotes in it, the ' character. In between the single quotes is the data I want.

How can I write a regex to extract "the data i want" from the following text?

mydata = "some string with 'the data i want' inside"; 
like image 473
asdasd Avatar asked Jan 11 '11 20:01

asdasd


People also ask

How do I find substrings in regex?

String indexOf() Method The most common (and perhaps the fastest) way to check if a string contains a substring is to use the indexOf() method. This method returns the index of the first occurrence of the substring. If the string does not contain the given substring, it returns -1.

How do you extract a substring from a string in Python regex?

Use re.search() to extract a substring matching a regular expression pattern. Specify the regular expression pattern as the first parameter and the target string as the second parameter. \d matches a digit character, and + matches one or more repetitions of the preceding pattern.

How do I capture a word in regex?

To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.


2 Answers

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 
like image 175
Mark Byers Avatar answered Sep 16 '22 23:09

Mark Byers


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, "'"); 
like image 28
Beothorn Avatar answered Sep 20 '22 23:09

Beothorn