鉴于此字符串:
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次出现。
我一直在努力理解boundaries和anchors但到目前为止无法将它们应用于此上下文。
谢谢!
答案 0 :(得分:1)
您的问题出在正则表达式中。你使用的正则表达式是:
if let value = json\["([^\)]*)"\] ......
右边的那一点究竟意味着什么? Here is a visualisation
你为什么要绕过"除了结束括号之外的任何东西"? 此是导致您的匹配跨越多行的原因。
相反,你应该使用的是"除了"
字符以外的任何字符",即
if let value = json\["([^"]*)"\] ......
答案 1 :(得分:1)
你做错了。这是正确的正则表达式
json\["([^\]]*)"\]\.int \{ self\.([^}]*) = value \}
<强> Regex Demo 强>
正则表达式中的错误
i).
代表任何角色。您需要将.
作为\.
转义,以便与字面上的.
匹配
ii)您使用的是\["([^\)]*)"\]
,但是您需要使用["([^]]*)"\]
,因为除了]
而不是)
之外,您还需要匹配任何内容。您甚至可以使用["([^"]*)"\]
iii)您使用的是([^\)]*)
,但需要使用([^}]*)
或([^\s]*)
或([^=]*)