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

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

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

当前回答

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

在javascript中:

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

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

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

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

它更干净。

你不需要正则表达式。

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

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