461

我有一个字符串,其中有两个单引号,即'字符。单引号之间是我想要的数据。

如何编写正则表达式以从以下文本中提取“我想要的数据”?

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

14 回答 14

678

假设您想要单引号之间的部分,请将此正则表达式与 a 一起使用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));
}

结果:

我想要的数据
于 2011-01-11T20:27:45.733 回答
79

你不需要正则表达式。

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

String dataYouWant = StringUtils.substringBetween(mydata, "'");
于 2013-03-13T20:37:23.447 回答
17
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));
        }

    }
}
于 2011-01-11T20:40:47.527 回答
16

有一个简单的单线:

String target = myData.replaceAll("[^']*(?:'(.*?)')?.*", "$1");

通过使匹配组成为可选的,这也满足了在这种情况下通过返回空白未找到引号的情况。

现场演示

于 2017-01-14T23:29:13.647 回答
10

因为您还勾选了 Scala,这是一个没有正则表达式的解决方案,可以轻松处理多个引用字符串:

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)
于 2011-01-11T21:03:46.103 回答
7
String dataIWant = mydata.replaceFirst(".*'(.*?)'.*", "$1");
于 2017-09-13T08:28:21.557 回答
6

从 Java 9 开始

从这个版本开始,您可以使用一种Matcher::results不带 args 的新方法,该方法能够轻松地返回Stream<MatchResult>whereMatchResult表示匹配操作的结果,并提供读取匹配组等内容(该类自 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...)

上面的代码片段导致:

the data I want
another data I want

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

于 2020-10-15T22:28:46.603 回答
3

如在 javascript 中:

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

实际的正则表达式是:/'([^']+)'/

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

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

它更干净。

于 2011-01-11T20:26:49.263 回答
2

String dataIWant = mydata.split("'")[1];

观看现场演示

于 2017-08-16T13:15:17.080 回答
1

Apache Commons Lang 为 java.lang API 提供了许多帮助实用程序,最值得注意的是字符串操作方法。在您的情况下,开始和结束子字符串是相同的,所以只需调用以下函数。

StringUtils.substringBetween(String str, String tag)

获取嵌套在同一 String 的两个实例之间的 String

如果开始和结束子字符串不同,则使用以下重载方法。

StringUtils.substringBetween(String str, String open, String close)

获取嵌套在两个字符串之间的字符串。

如果您想要匹配子字符串的所有实例,请使用,

StringUtils.substringsBetween(String str, String open, String close)

在字符串中搜索由开始和结束标记分隔的子字符串, 返回数组中的所有匹配子字符串

对于有问题的示例,以获取匹配子字符串的所有实例

String[] results = StringUtils.substringsBetween(mydata, "'", "'");
于 2019-07-26T15:11:16.003 回答
0

在斯卡拉,

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
于 2011-01-11T22:32:48.367 回答
0

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

if (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);
于 2020-02-09T20:51:16.917 回答
0

一些小组(1)对我不起作用。我使用 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";
于 2020-06-10T13:11:45.823 回答
0

在pom.xml上添加apache.commons依赖项

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>

下面的代码有效。

StringUtils.substringBetween(String mydata, String "'", String "'")
于 2020-02-27T10:39:45.180 回答