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

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

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

当前回答

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

其他回答

String dataIWant = mydata.replaceFirst(".*'(.*?)'.*", "$1");

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

参见现场演示

在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 "'")

Apache Commons Lang为java提供了大量的辅助实用程序。lang API,最著名的是字符串操作方法。 在您的示例中,开始子字符串和结束子字符串是相同的,因此只需调用下面的函数。

stringutil的。substringBetween(String str, String标签) 获取嵌套在相同对象的两个实例之间的字符串 字符串。

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

stringutil的。substringBetween(String str, String open, String close) 获取嵌套在两个字符串之间的字符串。

如果你想要匹配子字符串的所有实例,那么使用,

stringutil的。substringsBetween(String str, String open, String close) 在String中搜索由开始和结束标记分隔的子字符串, 返回数组中所有匹配的子字符串。

对于所讨论的示例,获取匹配子字符串的所有实例

String[] results = StringUtils.substringsBetween(mydata, "'", "'");
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));
        }

    }
}