如何使用正则表达式和str.replace格式化

时间:2013-04-09 15:09:22

标签: javascript html regex

我正在使用这个正则表达式

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)并符合特定入住率的要求   根据第12章至第17章和第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) “。我得到这种格式?

4 个答案:

答案 0 :(得分:0)

在你的正则表达式中,尝试仅拆分在它们前面有空格的\(\d)\

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

答案 1 :(得分:0)

在parens数字之前寻找一些不是结束的东西。你必须在异常部分伪造它。我决定在“例外”这个词之前找到一个非字母的。这确保了一个完整的词,至少在前面。 (虽然,公平地说,我想不出一个以“表达”结尾的英文单词。)

注意JavaScript是如何通过正则表达式中的parens的顺序来对匹配的字符串进行编号,而不是在匹配器找到匹配的东西时按照parens的顺序进行编号。因此,不匹配的部分(因为或者)仍然计入$ 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

(这就是我为了让这个表达起作用而做的。)

答案 2 :(得分:0)

您可以将(?:\(\d+\))*合并到正则表达式中,除非我错过了您所追求的内容吗?

答案 3 :(得分:0)

使用

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

似乎有效:见http://jsbin.com/otuteh/1/edit