我有一个字符串,里面有两个单引号,'字符。在单引号之间是我想要的数据。
我怎么能写一个正则表达式提取“我想要的数据”从下面的文本?
mydata = "some string with 'the data i want' inside";
我有一个字符串,里面有两个单引号,'字符。在单引号之间是我想要的数据。
我怎么能写一个正则表达式提取“我想要的数据”从下面的文本?
mydata = "some string with 'the data i want' inside";
当前回答
这群人对我不起作用。我使用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";
其他回答
假设你想要单引号之间的部分,使用一个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
String dataIWant = mydata.split("'")[1];
参见现场演示
在javascript中:
mydata.match(/'([^']+)'/)[1]
实际的regexp是:/'([^']+)'/
如果你使用非贪婪修饰符(另一篇文章),它是这样的:
mydata.match(/'(.*?)'/)[1]
它更干净。
String dataIWant = mydata.replaceFirst(".*'(.*?)'.*", "$1");
在Scala中,
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