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";
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.
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.
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.
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, "'");
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