我在正则表达式方面很糟糕,非常感谢任何有关此问题的帮助,我认为这对于任何熟悉的人来说都是新东西。
我从 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 的分割功能可以做到这一点,但不幸的是它不允许使用两个单独的分隔符,因为这样我就可以在翻译之前指定文本。
为了简化,我所坚持的是正则表达式来收集translatedText“:”和下一个“
之间的任何内容如果有任何帮助,我将不胜感激
最佳答案
您可以使用 \"translatedText\":\"([^\"]*)\"
表达式来捕获匹配。
表达式含义如下:查找带引号的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));
此片段prints Ciao mondo
.
关于java - 正则表达式 - 文字字符串和引号之间的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10577096/