【问题标题】:regex - Replace multiple occurrences正则表达式 - 替换多次出现
【发布时间】:2018-10-04 19:27:15
【问题描述】:

我有一个字符串,可以是以下任何一种情况:

  1. test1/test2/test3/test4/test5/
  2. test1/test2/test3/test4//
  3. test1/test2/test3///
  4. test1/test2////
  5. test1/////

我的预期结果是

  1. test1/test2/test3/test4/test5
  2. test1/test2/test3/test4

  3. test1/test2/test3

  4. test1/test2
  5. 测试1 如何使用正则表达式实现?

目前,我正在使用 regexp_replace(col, "/+/", "/") 它正在工作,但最后留下了一个额外的 /。

【问题讨论】:

  • /处拆分,过滤掉数组中的空字符串,加入/
  • my answer 有帮助吗?

标签: regex apache-spark-sql impala


【解决方案1】:

你可以使用

regexp_replace(col, '/+$|(/){2,}', '\\1')

请参阅regex demo

详情

  • /+$ - 字符串末尾有 1 个或多个 /
  • | - 或
  • (/){2,} - 两个或多个斜杠,其中最后一个将保存在捕获组 1 中,您可以使用 \1 占位符从替换模式中引用它。

【讨论】:

    【解决方案2】:

    您可以使用以下正则表达式:

    /\/+$/gm
    

    并替换为空字符串 ('')。

    正则表达式将匹配字符串末尾的一个或多个斜杠,然后将其替换为空字符串,这意味着路径将不再以斜杠结尾。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 2013-09-29
      相关资源
      最近更新 更多