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

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

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

其他回答

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 dataIWant = mydata.split("'")[1];

参见现场演示

你可以用这个 我使用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);

这里有一个简单的语句:

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

通过将匹配组设置为可选,还可以通过在这种情况下返回空白来满足找不到引号的需求。

见现场演示。

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