选择""(包括)中的所有文字:但不包括:

时间:2015-07-20 22:45:39

标签: java regex

something.random-string.us-west-2.rds.amazonaws.com

我的数据看起来像上面那样 我想要选择的是""中的所有文字。这是在右边:那是包括""标记

我得到的是

CNAME

但它选择了:也不是我想要的。

3 个答案:

答案 0 :(得分:1)

如果必须使用正则表达式,可以尝试找到here的Matcher.group()方法。

InstrumentedList

这导致以下内容:

public class TestClass {
    public static void main(String[] args) {
        String input = "aa: {\n" +
                "    one: \"hello\",\n" +
                "    two: \"good\",\n" +
                "    three: \"bye\",\n" +
                "    four: \"tomorrow\",\n" +
                "  },\n" +
                "  \"bb\": {\n" +
                "    \"1\": \"a quick fox\",\n" +
                "    \"2\": \"a slow bird\",\n" +
                "    \"3\": \"a smart dog\",\n" +
                "    \"4\": \"a wilf flowert\",\n";
        // the actual code you need
        Pattern pattern = Pattern.compile("(: )(\".+\")");
        Matcher match = pattern.matcher(input);
        while (match.find()) {
            // here you go, only the value without the :
            String value = match.group(2);
            System.out.println("Found one = " + value);
        }
    }
}

答案 1 :(得分:1)

试试这个:

    String p = "(?<=:\\s{0,10})\"[^\"]*\"";
    Pattern pat = Pattern.compile(p);
    String s = 
        "aa: {\n" +
        "        one: \"hello\",\n" +
        "        two: \"good\",\n" +
        "        three: \"bye\",\n" +
        "        four: \"tomorrow\",\n" +
        "" +
        "    },\n" +
        "    \"bb\": {\n" +
        "        \"1\": \"a quick fox\",\n" +
        "        \"2\": \"a slow bird\",\n" +
        "        \"3\": \"a smart dog\",\n" +
        "        \"4\": \"a wilf flowert\",\n";
    Matcher m = pat.matcher(s);
    while (m.find())
        System.out.println(m.group());

结果:

"hello"
"good"
"bye"
"tomorrow"
"a quick fox"
"a slow bird"
"a smart dog"
"a wilf flowert"

答案 2 :(得分:1)

一个可能的正则表达式是: (?<=\: )\"*.*\"

(?<=\: )检查预期字符串之前是否有冒号,但不在正则表达式选择中选择它。其余的选择引号和它们所包围的字符串。

String testData = "test: \"Hello\"";
Pattern p = Pattern.compile("(?<=\\: )\\\"*.*\\\"");
Matcher m = p.matcher(testData);
while (m.find()) {
    System.out.println(testData.substring(m.start(), m.end()));
}

我强烈建议使用与正则表达式相反的JSON解析器,如fge所建议的那样。 即使你的代码在技术上不是有效的JSON,它也会更有效率,你可以避免重新发明轮子。