【问题标题】:Python REGEX returns additional string data than regex101 PythonPython REGEX 返回比 regex101 Python 更多的字符串数据
【发布时间】:2017-01-25 21:50:44
【问题描述】:

我有一些正则表达式的EXAMPLE HERE 可以找到纬度,这在示例中似乎很有效。我将其转移到 python 并使用匹配打印行,然后使用匹配字符串

line = "position:      0.00ft Northing:    728398.54  ft    Latitude:         31     38    40.268 N"
Lat = re.findall(r"\d{1,3}.*\s\d{1,2}.*\s\d{1,2}.*N",line.translate(None, '\x00'))
if len(Lat) > 0:
  print(line)
  latitude = Lat[0]
  print(latitude)
# 728398.54  ft    Latitude:         31     38    40.268 N

我的正则表达式哪里出错了?

我希望返回:“31 38 40.268 N”

【问题讨论】:

  • 请解释为什么您看到的结果是错误的。
  • 该行是第二个输出块,匹配是第一个输出块。如您在示例中看到的结果是,我正在寻找纬度值,即“31 38 40.268 N”@DYZ
  • 在 regex101 中,您使用的是惰性点匹配模式,.*?。在这里,你展示了贪婪的点,.*。这些数据似乎与您在 Python 中的数据与您在 regex101 上共享的数据不同。
  • @WiktorStribiżew 这不会影响结果
  • @DYZ 因为我的文本中到处都是空字节,你运行的是什么版本的 python 这可能是我的问题吗?我返回的正是我放在这里的东西

标签: python regex string


【解决方案1】:

这个正则表达式怎么样:Latitude:\s*(\d{1,3})\s*(\d{1,2})\s*(\d{1,2}(?:\.\d+)?),第 1 组中的度数,第 2 组中的分钟和第 3 组中的秒

import re
line = "position:      0.00ft Northing:    728398.54  ft    Latitude:         31     38    40.268 N"
result = re.search(r"Latitude:\s*(\d{1,3})\s*(\d{1,2})\s*(\d{1,2}(?:\.\d+)?)", line)
formatted = result.group(1) + " " + result.group(2) + " " + result.group(3) + " N"
print(formatted)

【讨论】:

  • 虽然这是一个有趣的解决方案,但 Latitude 这个词可能根本不存在或拼写错误,因此优先匹配模式而不是使用 latitude 作为标记
  • 去掉就行了,如果格式只用于纬度还是可以的。
  • 不幸的是,组方法也不适合我
猜你喜欢
  • 2022-07-24
  • 2011-09-16
  • 2018-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
  • 2017-05-05
相关资源
最近更新 更多