我有一个字符串,里面有两个单引号,'字符。在单引号之间是我想要的数据。
我怎么能写一个正则表达式提取“我想要的数据”从下面的文本?
mydata = "some string with 'the data i want' inside";
我有一个字符串,里面有两个单引号,'字符。在单引号之间是我想要的数据。
我怎么能写一个正则表达式提取“我想要的数据”从下面的文本?
mydata = "some string with 'the data i want' inside";
当前回答
因为你还勾选了Scala,这是一个没有regex的解决方案,可以轻松处理多个带引号的字符串:
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)
其他回答
这里有一个简单的语句:
String target = myData.replaceAll("[^']*(?:'(.*?)')?.*", "$1");
通过将匹配组设置为可选,还可以通过在这种情况下返回空白来满足找不到引号的需求。
见现场演示。
你不需要正则表达式。
将apache commons lang添加到您的项目(http://commons.apache.org/proper/commons-lang/),然后使用:
String dataYouWant = StringUtils.substringBetween(mydata, "'");
在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
你可以用这个 我使用while循环存储所有匹配子字符串在数组中,如果你使用
如果(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);
因为你还勾选了Scala,这是一个没有regex的解决方案,可以轻松处理多个带引号的字符串:
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)