【问题标题】:How to find and replace space between digits in a string column?如何查找和替换字符串列中数字之间的空格?
【发布时间】:2019-10-18 23:40:21
【问题描述】:

我需要使用正则表达式查找和替换长字符串中数字之间的任何空格。

我尝试使用诸如[0-9][\s][0-9] 之类的正则表达式,然后使用诸如.withColumn('free_text', regexp_replace('free_text', '[0-9][\s][0-9]', '')) 之类的regexp_replace。 但是,正则表达式匹配 1(space)4 我只想拥有 (space)

这是一个例子:

我有什么: "Hello. I am Marie. My number is 768 990"

我想要的: "Hello. I am Marie. My number is 768990"

谢谢,

【问题讨论】:

    标签: regex pyspark regexp-replace


    【解决方案1】:

    这是使用捕获组的一种方法:

    .withColumn('free_text', regexp_replace('free_text', '([0-9])\s([0-9])', '$1$2'))
    

    这里的想法是匹配 捕获由它们之间的空白字符分隔的两个数字。然后,我们可以只替换相邻的两个数字。

    【讨论】:

      【解决方案2】:

      您的模式匹配一​​个数字、空白字符和一个数字。请注意,\s 也匹配换行符。

      如果支持,您可以使用环视而不是匹配数字:

      (?<=[0-9])\s(?=[0-9])
      
      
      .withColumn('free_text', regexp_replace('free_text', '(?<=[0-9])\s(?=[0-9])', ''))
      

      【讨论】:

      • 不确定该函数是否支持环视。但是看看这个页面,regexp_extract 函数接受一个 Java 正则表达式。
      猜你喜欢
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      相关资源
      最近更新 更多