Hive - 从字符串中删除子字符串

时间:2016-02-27 09:11:16

标签: java regex hive udf

我需要用空字符串替换给定字符串中的子字符串,子字符串出现在字符串的不同位置。

我想从这些可能的字符串组合中删除"fruit":"apple"并期望相应的字符串:

{"client":"web","fruit":"apple"}   --> {"client":"web"}
{"fruit":"apple","client":"web"}   --> {"client":"web"}
{"client":"web","fruit":"apple","version":"v1.0"} --> {"client":"web","version":"v1.0"}
{"fruit":"apple"}   -->  null or empty string

我使用了regexp_replace(str, "\,*\"fruit\"\:\"apple\"", ""),但这并没有给我预期的结果。构建正则表达式的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您似乎正在使用JSON格式的数据。根据所包含的依赖关系,您可以完全实现它而无需正则表达式。

例如,如果您使用的是Google的lib Gson,那么您可以将String解析为JsonObject,然后从中删除属性

String input = "your data";
JsonParser parser = new JsonParser();
JsonObject o = parser.parse(input).getAsJsonObject();

try {
   String foundValue = o.getAsJsonPrimitive("fruit").getAsString();
   if ("apple".equals(foundValue)) {
      o.remove("fruit");
   }
} catch (Exception e) {
  e.printStackTrace();
}
String filteredData = o.toJSONString();

P.S。代码不是最终版本,它可能需要处理某些情况(当没有这样的字段,或者它包含非原始值时),需要进一步的细节来覆盖它

P.P.S。 IMO,在这种情境中使用正则表达式使代码的可读性和灵活性降低

相关问题