gpt4 book ai didi

regex - 如何防止正则表达式超出字符串/行的末尾

转载 作者:搜寻专家 更新时间:2023-11-01 07:24:44 25 4
gpt4 key购买 nike

给定这个字符串:

if let value = json["PropertyID"].int { self.propertyID = value }

我已经成功匹配并替换为这个:

self.propertyID = representation.valueForKey("PropertyID")?.integerValue

注意整个字符串都改变了,除了 propertyID"PropertyID" 被重新用于构建新字符串

因此,应用此正则表达式:

// Match
if let value = json\["([^\)]*)"\].int \{ self.([^\)]*) = value \}
// Replace
self.$2 = representation.valueForKey("$1")?.integerValue

结果输出是这个格式完美的字符串:

self.propertyID = representation.valueForKey("PropertyID")?.integerValue

到目前为止一切顺利!但是,我尝试匹配和替换的文本/代码文件实际上看起来更像这样:

if let value = json["PropertyID"].int { self.propertyID = value }
if let value = json["UniqueID"].string { self.propertyUniqueID = value }
if let value = json["TypologyDescription"].string { self.typology = value }
if let value = json["RoomsNumber"].int { self.bedrooms = value }
if let value = json["BathroomsNumber"].int { self.bathrooms = value }
if let value = json["GrossBuiltArea"].decimal { self.grossBuiltArea = value }
if let value = json["TotalLandArea"].decimal { self.totalLandArea = value }
if let value = json["CurrentAskingPrice"].decimal { self.price = value }
if let value = json["CurrencyDescription"].string { self.currency = value }
if let value = json["CountryDescription"].string { self.country = value }
if let value = json["DistrictDescription"].string { self.district = value }
if let value = json["CountyDescription"].string { self.county = value }
if let value = json["ParishDescription"].string { self.parish = value }
if let value = json["Latitude"].decimal { self.latitude = value }
if let value = json["Longitude"].decimal { self.longitude = value }
if let value = json["DefaultPhotoID"].int { self.defaultPhotoID = value }
if let value = json["PropertyStageStatus"].string { self.propertyStageStatusDescription = value }
if let value = json["PropertyStageSubStatus"].string { self.propertyStageSubStatusDescription = value }

此时,正则表达式似乎并不关心边界。它匹配整个文本而不是多次出现(在此示例中我期望出现 4 次)。

我明白为什么会这样!只是还不知道如何克服它...我需要它从 "if" 开始并在 "}" 结束并且不要超出那条线!给我 4 次出现而不是整个文本/代码作为 1 次出现。

我一直在努力理解boundariesanchors但到目前为止无法将它们应用于这种情况。

谢谢!

最佳答案

你做错了。这是正确的正则表达式

json\["([^\]]*)"\]\.int \{ self\.([^}]*) = value \}

Regex Demo

正则表达式中的错误

i) . 代表任意字符。您需要将 . 转义为 \. 以匹配 . 字面意思

ii) 您正在使用 \["([^\)]*)"\] 但您需要使用 ["([^]]*)"\] 因为你想匹配除 ] 而不是 ) 之外的任何内容。您甚至可以使用 ["([^"]*)"\]

iii) 您正在使用 ([^\)]*) 但您需要使用 ([^}]*)([^\s]*)([^=]*)

关于regex - 如何防止正则表达式超出字符串/行的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36861432/

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