java - two - regex substring example

How to extract a substring using regex (7)

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 dataIWant = mydata.split("'")[1];

See Live Demo

Assuming you want the part between single quotes, use this regular expression with a Matcher:



String mydata = "some string with 'the data i want' inside";
Pattern pattern = Pattern.compile("'(.*?)'");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())


the data i want

I agree with the answer above by Mihai Toader works like a charm. Just a small modification to it based on the updates.

let string = "fact-tab-1 extra stuff you dont care about"

let matchResult = string.match(/fact-tab-./);


console.log('The extracted part would be : ' + matchResult[0])
document.getElementById('result').innerHTML = 'The extracted part would be : ' + matchResult[0];
<div id="result">

Running Example : JSFiddle

In Scala,

val ticks = "'([^']*)'".r

ticks findFirstIn mydata match {
    case Some(ticks(inside)) => println(inside)
    case _ => println("nothing")

for (ticks(inside) <- ticks findAllIn mydata) println(inside) // multiple matches

val Some(ticks(inside)) = ticks findFirstIn mydata // may throw exception

val ticks = ".*'([^']*)'.*".r    
val ticks(inside) = mydata // safe, shorter, only gets the first set of ticks

as in javascript:


the actual regexp is: /'([^']+)'/

if you use the non greedy modifier (as per another post) it's like this:


it is cleaner.

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()) {