2016-04-26 25 views
1

的末尾:如何防止一個正則表達式表達超越鑑於這種字符串的字符串/線路

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)。

我明白爲什麼會發生這種情況!只是沒有如何克服它呢...我需要它開始於「如果」和結束於「}」並且不要超越該行!給我4個事件,而不是整個文本/代碼作爲單個事件。

我一直在試圖理解boundariesanchors,但是迄今爲止還無法將它們應用到此上下文中。

謝謝!

回答

1

你做錯了。這是正確的正則表達式

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

Regex Demo

誤區你的正則表達式

我).代表任意字符。你需要逃避.\.字面上

ii)您正在使用\["([^\)]*)"\]匹配.,但你需要使用["([^]]*)"\]因爲你想,除了])匹配任何東西。你甚至可以使用["([^"]*)"\]

III)您使用的([^\)]*)但你需要使用([^}]*)([^\s]*)([^=]*)

1

你的問題是在正則表達式中。您使用的正則表達式是:

if let value = json\["([^\)]*)"\] ...... 

右邊的那個實際上是什麼意思? Here is a visualisation

你爲什麼要循環「除括號外的任何內容」? 這是是什麼導致您的匹配通過多行。

相反,你應該使用什麼是「什麼,但一個"性格」,即

if let value = json\["([^"]*)"\] ......