正则表达式-替换多个匹配项

时间:2018-10-04 19:27:15

标签: regex apache-spark-sql impala

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

  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. test1 如何使用正则表达式实现?

当前,我正在使用regexp_replace(col,“ / + /”,“ /”),但最后还是留了一个额外的/。

2 个答案:

答案 0 :(得分:0)

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

/\/+$/gm

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

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

答案 1 :(得分:0)

您可以使用

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

请参见regex demo

详细信息

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