我有一个字符串,里面有两个单引号,'字符。在单引号之间是我想要的数据。

我怎么能写一个正则表达式提取“我想要的数据”从下面的文本?

mydata = "some string with 'the data i want' inside";

当前回答

在javascript中:

mydata.match(/'([^']+)'/)[1]

实际的regexp是:/'([^']+)'/

如果你使用非贪婪修饰符(另一篇文章),它是这样的:

mydata.match(/'(.*?)'/)[1]

它更干净。

其他回答

String dataIWant = mydata.replaceFirst(".*'(.*?)'.*", "$1");
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));
        }

    }
}

从Java 9开始

在这个版本中,你可以使用不带参数的新方法Matcher::results,它能够轻松地返回Stream<MatchResult>,其中MatchResult表示匹配操作的结果,并提供读取匹配的组和更多信息(这个类从Java 1.5开始就知道了)。

String string = "Some string with 'the data I want' inside and 'another data I want'.";

Pattern pattern = Pattern.compile("'(.*?)'");
pattern.matcher(string)
       .results()                       // Stream<MatchResult>
       .map(mr -> mr.group(1))          // Stream<String> - the 1st group of each result
       .forEach(System.out::println);   // print them out (or process in other way...)

上面的代码片段导致:

我想要的数据 我想要的另一个数据

与过程性的if (matcher.find())和while (matcher.find())检查和处理相比,最大的优势在于当有一个或多个结果可用时使用起来更容易。

在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

你不需要正则表达式。

将apache commons lang添加到您的项目(http://commons.apache.org/proper/commons-lang/),然后使用:

String dataYouWant = StringUtils.substringBetween(mydata, "'");