Hive查询替换字符串中仅第一次出现的子字符串

4
我需要替换给定字符串中第一次出现的子字符串。例如,如果字符串是"My name is Adam",我想把第一个 "a" 替换成 "@"。因此,我想要的输出是"My n@me is Adam"。在MySQL中,有一个函数regexp_replace,它有一个可选参数occurrence,用于指定要替换多少次。但不幸的是,在hive函数中没有这个可选参数。你有什么建议吗?
1个回答

6
hive> select regexp_replace('My name is Adam','^(.*?)a','$1@');
OK
My n@me is Adam
Time taken: 0.061 seconds, Fetched: 1 row(s)

Pattern '^(.*?)a' 的含义为:

  ^ - the beginning of the string
.*? - any character (.) zero or more times (*) not greedy (?)
 () - remember group, we will refer it in the replacement string as $1
  a - 'a' character literally

替换字符串'$1@'的含义是:

$1 - group number one in the pattern (everything before 'a')
 @ - '@' character literally

您可以在regex101.com上调试正则表达式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接