2013-04-09 35 views
0

我使用正則表達式如何使用正則表達式和str.replace

var str = "The requirements of this chapter apply to the following: (1)New buildings or portions thereof used as health care occupancies (see 1.4.1) (2)Additions made to, or used as, a health care occupancy (see 4.6.6 and 18.1.1.4) Exception: The requirement of 18.1.1.1.1 shall not apply to additions classified as occupancies other than health care that are separated from the health care occupancy in accordance with 18.1.2.1(2) and conform to the requirements for the specific occupancy in accordance with Chapters 12 through 17 and Chapters 20 through 42, as appropriate. (3)Alterations, modernizations, or renovations of existing health care occupancies (see 4.6.7 and 18.1.1.4) (4)Existing buildings or portions thereof upon change of occupancy to a health care occupancy (see 4.6.11) Exception*: Facilities where the authority having jurisdiction has determined equivalent safety has been provided in accordance with Section 1.5."; 
str = str.replace(/(\(\d+\)|exception\s*\:*)/gi, "<br /><br />$1&nbsp"); 

格式化,我得到這樣

18.1.1.1.1本章的要求適用於輸出以下內容:

(1)用作其保健佔用新的建築物或部分 (見1.4.1)

(2)添置製作,或作爲,保健佔用(參見4.6.6 和18.1.1.4)

例外:的18.1.1.1.1的規定不應適用於分類爲佔用增加 比與18.1.2.1

(2),並遵守在 根據通過17第12和20章42通過爲特定的佔用要求,作爲分離 從按照保健佔用保健其他 合適。

(3)的改變,現代化,或者現有的衛生保健 佔有的整修(參見4.6.7和18.1.1.4)

(4)時佔用的變化 健康護理它們的現有建築物或部分入住(見4.6.11)

但我期望的輸出是

18.1.1.1.1本章的要求適用於以下內容:

(1)用作其保健佔有率 (見1.4.1)新建築物或部分

(2)添置製成,或用作,衛生保健佔用(參見4.6.6和 18.1.1.4)(2),並根據第12章至第17章和第20章 至42條的規定,符合具體的 入住的要求。

例外:的18.1.1.1.1要求不適用於分類爲比與18.1.2.1

(3)的改變中分離 從按照保健佔用保健其他佔有率增加 ,現代化,或者現有的衛生保健 佔有的整修(參見4.6.7和18.1.1.4)

(4)現有建築物或部分時佔用的變化 保健佔用它們的(見4.6.11)

這打破了(2)行再此值「(參見4.6.6和18.1.1.4)(2)」。怎麼能我得到這個格式?

+3

當您張貼,請使用標記的代碼!就目前來看,這是不可讀的。 – epascarello 2013-04-09 15:10:09

+1

TL; DR:他希望在編號行(行首)分割他的字符串,但不是行的一部分'(2)'。 – 2013-04-09 15:14:56

回答

0

在您正則表達式,儘量只在拆分\(\d)\ s表示面前有一個空格:

str = str.replace(/(\s\(\d+\)|exception\s*\:*)/gi, "<br /><br />$1&nbsp"); 
0

看的東西是在括號的數量不前關閉括號。你必須在異常部分僞造它。我決定在「例外」一詞之前找到一個非字母表。這確保了它的整個說法,至少在前面。 (儘管公平地說,我想不出一個以「表達式」結尾的英文單詞。)

請注意,JavaScript是如何通過正則表達式中的parens的順序來編號匹配的字符串,而不是通過順序匹配者通過尋找匹配的東西來尋找匹配對象。所以不匹配的部分(因爲or)仍然計入$ 1,$ 2,$ 3和$ 4。

str = str.replace(/([^)])(\(\d+\))|([^a-zA-Z])(exception\s*\:*)/gi, "$1$3<br /><br />$2$4&nbsp"); 

您可以測試JavaScript正則表達式在這裏:http://www.regexplanet.com/advanced/javascript/index.html

(這是我做了什麼讓那表情工作)

0

您可以納入(?:\(\d+\))*到你的正則表達式,除非我已經錯過了什麼你在追求?