0

我在正则表达式方面很糟糕,非常感谢任何关于这个问题的帮助,我认为这对于任何熟悉的人来说都是新东西。

我从 REST 调用中得到这样的响应

    {"responseData":{"translatedText":"Ciao mondo"},"responseDetails":"","responseStatus":200,"matches":[{"id":"424913311","segment":"Hello World","translation":"Ciao mondo","quality":"74","reference":"","usage-count":50,"subject":"All","created-by":"","last-updated-by":null,"create-date":"2011-12-29 19:14:22","last-update-date":"2011-12-29 19:14:22","match":1},{"id":"0","segment":"Hello World","translation":"Ciao a tutti","quality":"70","reference":"Machine Translation provided by Google, Microsoft, Worldlingo or the MyMemory customized engine.","usage-count":1,"subject":"All","created-by":"MT!","last-updated-by":null,"create-date":"2012-05-14","last-update-date":"2012-05-14","match":0.85}]}

我所需要的只是这些引文之间的“Ciao mondo”。我希望使用 Java 的拆分功能可以做到这一点,但不幸的是它不允许两个单独的分隔符,因为我可以在翻译之前指定文本。

为简化起见,我坚持使用正则表达式来收集 translateText":" 和下一个 "

我会非常感谢任何帮助

4

3 回答 3

3

您可以使用\"translatedText\":\"([^\"]*)\"表达式来捕获匹配项。

表达式含义如下:find 引用translatedText后跟一个冒号和一个开引号。然后匹配以下引号之前的每个字符,并将结果捕获到捕获组中。

String s = " {\"responseData\":{\"translatedText\":\"Ciao mondo\"},\"responseDetails\":\"\",\"responseStatus\":200,\"matches\":[{\"id\":\"424913311\",\"segment\":\"Hello World\",\"translation\":\"Ciao mondo\",\"quality\":\"74\",\"reference\":\"\",\"usage-count\":50,\"subject\":\"All\",\"created-by\":\"\",\"last-updated-by\":null,\"create-date\":\"2011-12-29 19:14:22\",\"last-update-date\":\"2011-12-29 19:14:22\",\"match\":1},{\"id\":\"0\",\"segment\":\"Hello World\",\"translation\":\"Ciao a tutti\",\"quality\":\"70\",\"reference\":\"Machine Translation provided by Google, Microsoft, Worldlingo or the MyMemory customized engine.\",\"usage-count\":1,\"subject\":\"All\",\"created-by\":\"MT!\",\"last-updated-by\":null,\"create-date\":\"2012-05-14\",\"last-update-date\":\"2012-05-14\",\"match\":0.85}]}";
System.out.println(s);
Pattern p = Pattern.compile("\"translatedText\":\"([^\"]*)\"");
Matcher m = p.matcher(s);
if (!m.find()) return;
System.out.println(m.group(1));

此片段打印Ciao mondo

于 2012-05-14T03:25:31.947 回答
0

使用前瞻和后瞻来收集引号内的字符串: (?<=[,.{}:]\").*?(?=\")

class Test
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        String in = scanner.nextLine();

        Matcher matcher = Pattern.compile("(?<=[,.{}:]\\\").*?(?=\\\")").matcher(in);

        while(matcher.find())
            System.out.println(matcher.group());
    }
}
于 2012-05-14T03:20:42.623 回答
0

试试这个正则表达式 -

^.*translatedText":"([^"]*)"},"responseDetails".*$

匹配组将包含文本 Ciao mondo。

这假定 translateText 和 responseDetails 将始终出现在您的示例中指定的位置。

于 2012-05-14T03:25:53.903 回答