gpt4 book ai didi

ruby - 解析地址的正则表达式

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:27 24 4
gpt4 key购买 nike

我正在尝试学习如何使用正则表达式来解析位置/地址字符串。不幸的是,我得到的数据与大多数地址的写入方式不一致且非常规。以下是我目前所拥有的,我遇到的问题是我需要多次解析字符串以将其归结为正确的格式。

以下面的字符串为例:102 Spruce, 108 Spruce, 110 Spruce, Greenwood, SC 29649 我想要的最终结果是110 Spruce, Greenwood, SC 29649

代码:

l = nil
location_str = "102 Spruce, 108 Spruce, 110 Spruce, Greenwood, SC 29649"
1.upto(4).each do |attempt|
l = Location.from_string(location_str)
puts "TRYING: #{location_str}"
break if !l.nil?
location_str.gsub!(/^[^,:\-]+\s*/, '')
end

输出:

TRYING: 102 Spruce, 108 Spruce, 110 Spruce, Greenwood, SC 29649
TRYING: , 108 Spruce, 110 Spruce, Greenwood, SC 29649
TRYING: , 108 Spruce, 110 Spruce, Greenwood, SC 29649
TRYING: , 108 Spruce, 110 Spruce, Greenwood, SC 29649

预期:

TRYING: 102 Spruce, 108 Spruce, 110 Spruce, Greenwood, SC 29649
TRYING: 108 Spruce, 110 Spruce, Greenwood, SC 29649
TRYING: 110 Spruce, Greenwood, SC 29649

最佳答案

这是不止一种方法的事情之一。这是另一个:

def address_from_location_string(location)
*_, address, city, state_zip = location.split(/\s*,\s*/)
"#{address}, #{city}, #{state_zip}"
end

address_from_location_string("102 Spruce, 108 Spruce, 110 Spruce, Greenwood, SC 29649")
# => "110 Spruce, Greenwood, SC 29649"

关于ruby - 解析地址的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39275355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com