2013-01-17 112 views
0

我有這個json文件。部分原因是如下:正則表達式匹配換行

{ "has_more" : false, 
    "items" : [ { "aliases" : [ "http://www.stackoverflow.com" ], 
     "api_site_parameter" : "stackoverflow", 
     "markdown_extensions" : [ "Prettify" ], 
     "name" : "Stack Overflow", 
     "related_sites" : [ { "name" : "Stack Overflow Chat", 
       "relation" : "chat", 
       "site_url" : "http://chat.stackoverflow.com" 
      } ], 
     "site_state" : "normal", 
     "site_type" : "main_site", 
     "site_url" : "http://stackoverflow.com", 
     "styling" : { "link_color" : "#0077CC", 
      "tag_background_color" : "#E0EAF1", 
      "tag_foreground_color" : "#3E6D8E" 
      } 
     }, 
     { "api_site_parameter" : "serverfault", 
     "markdown_extensions" : [ "Prettify" ], 
     "name" : "Server Fault", 
     "related_sites" : [ { "api_site_parameter" : "meta.serverfault", 
       "name" : "Meta Server Fault", 
       "relation" : "meta", 
       "site_url" : "http://meta.serverfault.com" 
      }, 
      { "name" : "Chat Stack Exchange", 
       "relation" : "chat", 
       "site_url" : "http://chat.stackexchange.com" 
      } 
      ], 
     "site_state" : "normal", 
     "site_type" : "main_site", 
     "site_url" : "http://serverfault.com", 
     "styling" : { "link_color" : "#10456A", 

我要匹配像

 "related_sites" : [ { "name" : "Stack Overflow Chat", 
       "relation" : "chat", 
       "site_url" : "http://chat.stackoverflow.com" 
      } ], 

 "related_sites" : [ { "api_site_parameter" : "meta.serverfault", 
       "name" : "Meta Server Fault", 
       "relation" : "meta", 
       "site_url" : "http://meta.serverfault.com" 
      }, 
      { "name" : "Chat Stack Exchange", 
       "relation" : "chat", 
       "site_url" : "http://chat.stackexchange.com" 
      } 
      ], 

串不啓用多。任何想法如何做到這一點?

+3

使用JSON解析器請。 「 – nhahtdh

回答

1

「啓用多行」正是您如何匹配多行。這就是爲什麼它被稱爲「多線」。但是,因爲它所做的只是將.更改爲包含\n,所以您可以改爲編寫(.|\n)

但鑑於這是JSON,爲什麼你在地球上使用正則表達式呢?只需將其解析爲數據結構並從那裏開始工作即可。

data = json.loads(json_string) 
for item in data['items']: 
    print item['related_sites'] 
+0

+1」但是鑑於這是JSON,爲什麼你要在其上使用正則表達式? – Srinivas

+0

我同意JSON解析在這裏是最好的,但有時你想要在IDE中進行搜索和替換,其中正則表達式可以訣竅 – Iftah

+0

如果您手動執行此操作,並且只需搜索一次'\ brelated_sites \ b'帶有確認和眼球每場比賽 – Eevee

0

如果有 「related_sites」 元素裏面沒有數組,然後嘗試:

"related_sites" : \[(?:[^\]]*\n?)*\]