hive translate()函數的使用


translate()這個函數工作中偶爾會用到,但是每次用都要忘記了改怎么使用,今天抽時間就徹底梳理一下該函數的使用時的一些細節。

  官方解釋
desc function extended translate;
translate(input, from, to) - translates the input string by replacing the characters present in the from string with the corresponding characters in the to string
translate(string input, string from, string to) is an equivalent function to translate in PostGreSQL. It works on a character by character basis on the input string (first parameter). A character in the input is checked for presence in the from string (second parameter). If a match happens, the character from to string (third parameter) which appears at the same index as the character in from string is obtained. This character is emitted in the output string  instead of the original character from the input string. If the to string is shorter than the from string, there may not be a character present at the same index in the to string. In such a case, nothing is emitted for the original character and it's deleted from the output string.
For example,
""
translate('abcdef', 'adc', '19') returns '1b9ef' replacing 'a' with '1', 'd' with '9' and removing 'c' from the input string
""
translate('a b c d', ' ', '') return 'abcd' removing all spaces from the input string
""
If the same character is present multiple times in the input string, the first occurence of the character is the one that's considered for matching. However, it is not recommended to have the same character more than once in the from string since it's not required and adds to confusion.
""
For example,
""
translate('abcdef', 'ada', '192') returns '1bc9ef' replaces 'a' with '1' and 'd' with '9' ignoring the second occurence of 'a' in the from string mapping it to '2'
先看下官方案例
select translate('abcdef', 'adc', '19') translate_exe
1b9ef
函數用法
translate(input,from,to)
  • input:輸入字符串
  • from:需要匹配的字符
  • to :用哪些字符來替換被匹配到的字符
注意點:這里from的字符與to字符在位置上存在一 一對應關系,也就是from中每個位置上的字符用to中對應位置的字符替換。
場景1、from 和 to 長度一樣,如translate("abcdef-abcdef","abcdef","123456");替換不是說把"abcdef"替換成"123456",而是把a替換成1,把b替換成2,把c替換成3,把d替換成4,e替換成5,f替換成6
select translate('abcdef-abcdef', 'abcd', '1234'),--1234ef-1234ef
       translate('abcdef-abcdef', 'ab', '12'),    --12cdef-12cdef
       translate('abcdef-abcdef', 'ad', '14'),    --1bc4ef-1bc4ef
       translate('abcdef-abcdef', 'da', '41');--1bc4ef-1bc4ef
場景2:from 字符串長度>to的字符串長度 ,例如translate('abcdef-abcdef','adbc','123')    意思是把 a替換為1,b替換為2,c替換為3,d替換為空,即刪除掉。
select translate('abcdef-abcdef', 'abcd', '123'), --123ef-123ef
       translate('abcdef-abcdef', 'adbc', '123'); --132ef-132ef
場景3 如果 from里有重復字符 比如abca,1231,重復的字符a對應to的替換不會起作用
select TRANSLATE ('abcdaabbaaabbb','aa','12')--1bcd11bb111bbb 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM