【问题标题】:Regex program to search a string with spaces and back slashes performance issue正则表达式程序搜索带有空格和反斜杠的字符串的性能问题
【发布时间】:2020-11-14 16:16:27
【问题描述】:

这些是我的文本行:

Region\ name=Provence\ Alpes\ Cote\ d'Azur shops=350,City=Nice 12345
Region\ name=Provence\ Alpes\ Cote\ d'Azur,City=Nice shopsabcdabcdabcdasssss=350 13456
City=Nice,Region\ name=Provence\ Alpes\ Cote\ d'Azur shopsabcdabcdabcdasssss=350 23456

输入:地区\名称
输出:Provence\ Alpes\ Cote\ d'Azur

输入:城市
输出:尼斯

以下解决方案提供了结果:

val data =List("Region\\ name=Provence\\ Alpes\\ Cote\\ d'Azur shops=350,City=Nice"
                ,"Region\\ name=Provence\\ Alpes\\ Cote\\ d'Azur,City=Nice shopsabcdabcdabcdasssss=350"
                ,"City=Nice,Region\\ name=Provence\\ Alpes\\ Cote\\ d'Azur shopsabcdabcdabcdasssss=350"
                ,"City=Nice,Region\\ name =unknown shops=350")
               //With that, let's extract all the values where target is the key.
val target  = """Region\\ name"""
val pattern =raw"$target\s*=((?:[\w'\\ -]+)+)(?:[ ,]+\w+=|,|$$)".r.unanchored
val output  = data.collect{ case pattern(m) => m }

但是当存在像shopsabcdabcdabcdasssssshopsabcdabcdabcdasssssssssssssssssssssss 这样的长字符串时,使用.r.unanchored 提取结果需要更多时间或挂起。

可以用更好的代码代替吗? 已解决,感谢您提供答案

regex101.com/r/nSYxfj/6 ----------->它可以用于提取整数值吗?或者我必须修改一些东西

【问题讨论】:

  • 你有什么问题?
  • 这很清楚,有灾难性的回溯需要修复。
  • south,attribute\ MO\ Name=A,MO\ Name=B SA\ Total=98 1590424200000000000 south,attribute\ MO\ Name=C,MO\ Name=D,SA\ Total=98 1590424200000000000 这里用户输入的是属性\ MO\ Name 和 MO\ Name ,我们在下面使用 regx val patternRegx =raw"(? A 当属性\ MO\ Name 和 B 当 MO\ Name
  • 请重新接受下面的答案,它完全解决了原来的问题。其余的在您的其他问题中讨论。

标签: java regex scala apache-spark


【解决方案1】:

((?:[\w'\\ -]+)+) 模式部分导致catastrophic backtracking

你需要使用

Region\\ name\s*=([\w'\\\s-]+)(?:[\s,]+\w+=|,|$)

请参阅regex demo

在 Scala 中,这样定义模式:

val pattern =raw"$target\s*=([\w'\\\s-]+)(?:[\s,]+\w+=|,|$$)".r.unanchored

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-09-22
  • 2015-07-14
  • 1970-01-01
  • 2012-11-22
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多