使用Scala,我正在尝试根据此问题从数据中删除URL。以下代码工作正常:
val removeRegexUDF = udf(
(input: Seq[String]) => input.filterNot(s => s.matches("(https?\://)\S+" ))
filteredDF.withColumn("noURL", removeRegexUDF('filtered)).select("racist", "filtered","noURL").show(100, false)
现在我想使用变量而不是文字正则表达式,所以我尝试:
val urls = """(https?\://)\S+"""
val removeRegexUDF = udf(
(input: Seq[String]) => input.filterNot(s => s.matches(urls ))
但这似乎对数据没有影响。我尝试:
val urls = """(https?\://)\S+""".r
但这会产生错误:
urls: scala.util.matching.Regex = (https?\://)\S+
<console>:45: error: type mismatch;
found : scala.util.matching.Regex
required: String
(input: Seq[String]) => input.filterNot(s => s.matches(urls) )
非常感谢有关如何实现这一目标的任何指导。
我想这与使用单引号与三引号有关。在第一个示例中,您放置了额外的反斜杠来转义字符,而在后一个示例中,您不需要它们 - 用三引号包装字符串就足够了。
println("(https?\://)\S+") // (https?://)S+
println("""(https?\://)\S+""") // (https?\://)\S+
println("""(https?://)S+""") // (https?://)S+