【问题标题】:Regex program to find a Number with spaces and back slashes正则表达式程序查找带有空格和反斜杠的数字
【发布时间】:2020-07-30 17:04:55
【问题描述】:

下面的正则表达式提取整数,但有一种情况失败。

示例字符串:

Monday,City=Nice,total\ avg\ shops=350,avg\ shops=20 month=jan
Monday,City=Nice total\ avg\ shops=23 avg\ shops=10 month=Feb
Monday,City=Nice total\,avg\ shops=30 avg\ shops=50 month=Feb
Monday total\,avg\,shops=30 avg\ shops=50,City=Nice month=Feb
Region,Network=myTelco total\ avg\ shops=30.0 avg\ shops=20color=Pink 1590424200000000000

我的正则表达式:

(?:(?<![^,])|=\w+\s+)avg\\ shops\s*=([0-9.]+)

demo link

示例代码:

 val matcherInt = Pattern.compile(s"(?:(?<![^,\\s])|=\\w+\\s+)$targetz\\s*=([0-9.]+)").matcher(valueInt)
     if (matcherInt.find()) {
      println( matcherInt.group(1))
     } else
      println("Nothing match")

【问题讨论】:

  • 请用当前输出和预期输出指定失败案例
  • @Anshuman 在演示链接中很清楚,Region,Network=myTelco total\ avg\ shops=30.0 avg\ shops=20color=Pink 1590424200000000000 没有匹配。

标签: regex scala


【解决方案1】:

你可以使用

(?:,|^|=[\w.]+\s+)avg\\ shops\s*=([0-9.]+)

regex demo

详情

  • (?:,|^|=[\w.]+\s+)
  • avg\\ shops - avg shops 字符串
  • \s* - 0 个或多个空格
  • = - = 符号
  • ([0-9.]+) - 捕获组 1:一位或多位数字或 . 字符。

【讨论】:

  • 会发生灾难性的回溯问题吗?
  • @santanumohanty 不,它不能出现在此处:,/字符串开头/= + 单词或点字符 + 空白字符,然后是 avg\ shops,然后是 0 个或多个空格,然后是 @ 987654337@,然后是 1 个或多个数字或点 - 如您所见,没有出现可能从同一位置开始的模式,后续模式都匹配不同类型的文本。
  • 你能检查一下,为什么它不匹配regex101.com/r/527Hlb/2
  • @santanumohanty 因为.后面不只有单词或点字符,试试regex101.com/r/527Hlb/3
  • 如果我得到像 -% 这样的特殊字符,那么它就会失败,例如 Region\ name=Provence-abc\ Alpes\ Cote\ d'Azu regex101.com/r/527Hlb/4
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
相关资源
最近更新 更多