java 取子字符串_java - 如何使用正则表达式提取子字符串

java - 如何使用正则表达式提取子字符串

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

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

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

10个解决方案

459 votes

假设您想要单引号之间的部分,请将此正则表达式与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

Mark Byers answered 2019-02-02T13:48:49Z

57 votes

你不需要正则表达式。

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

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

Beothorn answered 2019-02-02T13:49:19Z

9 votes

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

}

}

}

Sean McEligot answered 2019-02-02T13:49:34Z

9 votes

因为你还勾选了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)

Debilski answered 2019-02-02T13:49:56Z

6 votes

这有一个简单的单行:

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

通过使匹配组可选,这也适用于在这种情况下通过返回空白而找不到引号。

查看现场演示。

Bohemian answered 2019-02-02T13:50:28Z

5 votes

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

ZehnVon12 answered 2019-02-02T13:50:44Z

3 votes

在javascript中:

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

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

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

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

它更清洁。

Mihai Toader answered 2019-02-02T13:51:31Z

2 votes

在斯卡拉,

val ticks = "'([^']*)'".r

ticks findFirstIn mydata match {

case Some(ticks(inside)) => println(inside)

case _ => println("nothing")

}

for (ticks(inside)

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

Daniel C. Sobral answered 2019-02-02T13:51:54Z

1 votes

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

观看现场演示

ZehnVon12 answered 2019-02-02T13:52:24Z

0 votes

我同意Mihai Toader的上述答案,就像一个魅力。 只需对更新进行一次小修改即可。

运行示例:JSFiddle

kaushalop answered 2019-02-02T13:53:03Z

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值