【问题标题】:Hive query to replace only the first occurrence of a substringHive 查询仅替换第一次出现的子字符串
【发布时间】:2019-12-12 15:03:14
【问题描述】:

我需要替换给定字符串中第一次出现的子字符串。
例如,如果字符串是"My name is Adam",我想用"@" 替换第一个"a"
所以我想要的输出是"My n@me is Adam"
在 MySQL 中,有一个函数 regexp_replace,它有一个可选参数 occurrence 来指定要替换的出现次数。但不幸的是,hive 函数中不存在该可选参数。有什么建议吗?

【问题讨论】:

    标签: regex string hive hiveql regexp-replace


    【解决方案1】:
    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)
    

    模式'^(.*?)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

    【讨论】:

      猜你喜欢
      • 2011-08-25
      • 2014-03-21
      • 2021-04-17
      • 1970-01-01
      • 2016-12-19
      • 2020-05-22
      • 2016-05-07
      相关资源
      最近更新 更多