HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

How to extract a substring using regex

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howextractusingsubstringregex

Problem

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";

Solution

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

Code Snippets

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));
}

Context

Stack Overflow Q#4662215, score: 730

Revisions (0)

No revisions yet.