regex Javascript -从某个位置查找换行符的位置

vdzxcuhz  于 2023-03-09  发布在  Java
关注(0)|答案(2)|浏览(98)

我将以下文本存储在变量description中:

`This is a code update`

Official Name: 2011 New York City Electrical Code

Code Tile Name:

Reference: https://www.nyc.gov/site/buildings/codes/electrical-code.page

Citation: §27-3024

Doc Title: Local Law 39-2011, Local Law 99-2013, Local Law 39-2015

Source Doc: https://www.nyc.gov/assets/buildings/pdf/ll39of2011_electrical_code.pdf

Drive: https://drive.google.com/file/d/19Q0_G3VITpx0iCULtANMHqydAv0ZmvcF/view?usp=share_link

Effective Date: November 19, 2013 

**SCTOMJ**

我想提取与短语“Official Name”对应的数据,即“2011纽约市Electrical Code”。我使用了以下代码:

var official_name = description.search("Official Name:"); 
if(official_name != -1){
    official_name = description.substring(official_name + 14, description.indexOf("Code Tile Name:")).trim();
}

上面代码的问题是它依赖于短语“代码平铺名称:“的位置,这不应该是因为有时信息的排列会有所不同。我希望我的代码是序列独立的。有没有无论如何要在某个位置后获得第一个换行符?谢谢!

uinbv5nw

uinbv5nw1#

使用look behind assertion查找以“Official Name:“开头的行。正式名称后面的字符串应包含除换行符之外的所有字符。

注意:使用multiline标志(/m)使表达式^Official Name查找行的开头,而不是整个文本的开头。

const str = `\`This is a code update\`

Official Name: 2011 New York City Electrical Code

Code Tile Name:

Reference: https://www.nyc.gov/site/buildings/codes/electrical-code.page

Citation: §27-3024

Doc Title: Local Law 39-2011, Local Law 99-2013, Local Law 39-2015

Source Doc: https://www.nyc.gov/assets/buildings/pdf/ll39of2011_electrical_code.pdf

Drive: https://drive.google.com/file/d/19Q0_G3VITpx0iCULtANMHqydAv0ZmvcF/view?usp=share_link

Effective Date: November 19, 2013 

**SCTOMJ**`

const result = str.match(/(?<=^Official Name:)[^\n\r]+/m)

console.log(result?.[0].trim())
xdyibdwo

xdyibdwo2#

您还可以使用捕获组:

^Official Name:[ \t]*(.+)
    • 说明**
  • ^字符串开始
  • Official Name:逐字匹配
  • [ \t]*匹配可选空格或制表符
  • (.+)捕获组1,匹配1+次除换行符外的任何字符

Regex demo

const s = `\`This is a code update\`

Official Name: 2011 New York City Electrical Code

Code Tile Name:

Reference: https://www.nyc.gov/site/buildings/codes/electrical-code.page

Citation: §27-3024

Doc Title: Local Law 39-2011, Local Law 99-2013, Local Law 39-2015

Source Doc: https://www.nyc.gov/assets/buildings/pdf/ll39of2011_electrical_code.pdf

Drive: https://drive.google.com/file/d/19Q0_G3VITpx0iCULtANMHqydAv0ZmvcF/view?usp=share_link

Effective Date: November 19, 2013 

**SCTOMJ**`

const m = s.match(/^Official Name:[ \t]*(.+)/m)
if (m)
  console.log(m[1]);

相关问题