我有一个字符串,其中有两个单引号,即'
字符。单引号之间是我想要的数据。
如何编写正则表达式以从以下文本中提取“我想要的数据”?
mydata = "some string with 'the data i want' inside";
我有一个字符串,其中有两个单引号,即'
字符。单引号之间是我想要的数据。
如何编写正则表达式以从以下文本中提取“我想要的数据”?
mydata = "some string with 'the data i want' inside";
假设您想要单引号之间的部分,请将此正则表达式与 a 一起使用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));
}
结果:
我想要的数据
你不需要正则表达式。
将 apache commons lang 添加到您的项目(http://commons.apache.org/proper/commons-lang/),然后使用:
String dataYouWant = StringUtils.substringBetween(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));
}
}
}
有一个简单的单线:
String target = myData.replaceAll("[^']*(?:'(.*?)')?.*", "$1");
通过使匹配组成为可选的,这也满足了在这种情况下通过返回空白未找到引号的情况。
见现场演示。
因为您还勾选了 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)
String dataIWant = mydata.replaceFirst(".*'(.*?)'.*", "$1");
从这个版本开始,您可以使用一种Matcher::results
不带 args 的新方法,该方法能够轻松地返回Stream<MatchResult>
whereMatchResult
表示匹配操作的结果,并提供读取匹配组等内容(该类自 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...)
上面的代码片段导致:
the data I want another data I want
if (matcher.find())
与程序和while (matcher.find())
检查和处理相比,最大的优势在于当一个或多个结果可用时易于使用。
如在 javascript 中:
mydata.match(/'([^']+)'/)[1]
实际的正则表达式是:/'([^']+)'/
如果您使用非贪婪修饰符(根据另一篇文章),它是这样的:
mydata.match(/'(.*?)'/)[1]
它更干净。
String dataIWant = mydata.split("'")[1];
观看现场演示
Apache Commons Lang 为 java.lang API 提供了许多帮助实用程序,最值得注意的是字符串操作方法。在您的情况下,开始和结束子字符串是相同的,所以只需调用以下函数。
StringUtils.substringBetween(String str, String tag)
获取嵌套在同一 String 的两个实例之间的 String。
如果开始和结束子字符串不同,则使用以下重载方法。
StringUtils.substringBetween(String str, String open, String close)
获取嵌套在两个字符串之间的字符串。
如果您想要匹配子字符串的所有实例,请使用,
StringUtils.substringsBetween(String str, String open, String close)
在字符串中搜索由开始和结束标记分隔的子字符串, 返回数组中的所有匹配子字符串。
对于有问题的示例,以获取匹配子字符串的所有实例
String[] results = StringUtils.substringsBetween(mydata, "'", "'");
在斯卡拉,
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 循环将所有匹配的子字符串存储在数组中
if (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);
一些小组(1)对我不起作用。我使用 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";
在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 "'")