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

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

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

当前回答

假设你想要单引号之间的部分,使用一个Matcher正则表达式:

"'(.*?)'"

例子:

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

结果:

the data i want

其他回答

因为你还勾选了Scala,这是一个没有regex的解决方案,可以轻松处理多个带引号的字符串:

val text = "some string with 'the data i want' inside 'and even more data'"
text.split("'").zipWithIndex.filter(_._2 % 2 != 0).map(_._1)

res: Array[java.lang.String] = Array(the data i want, and even more data)

从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())检查和处理相比,最大的优势在于当有一个或多个结果可用时使用起来更容易。

这群人对我不起作用。我使用group(0)来查找url版本。

Pattern urlVersionPattern = Pattern.compile("\\/v[0-9][a-z]{0,1}\\/");
Matcher m = urlVersionPattern.matcher(url);
if (m.find()) { 
    return StringUtils.substringBetween(m.group(0), "/", "/");
}
return "v0";
String dataIWant = mydata.replaceFirst(".*'(.*?)'.*", "$1");

你可以用这个 我使用while循环存储所有匹配子字符串在数组中,如果你使用

如果(matcher.find ()) { System.out.println (matcher.group (1)); }

你会得到匹配子串所以你可以用这个来获取所有匹配子串

Matcher m = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+").matcher(text);
   // Matcher  mat = pattern.matcher(text);
    ArrayList<String>matchesEmail = new ArrayList<>();
        while (m.find()){
            String s = m.group();
            if(!matchesEmail.contains(s))
                matchesEmail.add(s);
        }

    Log.d(TAG, "emails: "+matchesEmail);