用于捕获第一次迭代的正则表达式

RegEx for capturing the first iteration

我有几个字符串想用正则表达式提取名称。整个名称与字符串的任何其他部分一样在一个或多个管道内。

每个字符串可能为空,部分示例:

"Women's College Hospital|76 Grenville Street|ACTT Clinic 6 East|Toronto ON  M5S 1B2"

""

"Health and Wellness Center|University of Toronto|214 College Street, Room 111|Toronto ON M5T 2Z9"

"Royal Health Care Centre|130 Adelaide St. West|Lower Concourse|P.O.Box 92|Toronto ON  M5H 3P5"

"Suite 1038|790 Bay Street|P.O. Box 51|Toronto ON  M5G 1N8
M5G 1N8"

"P.O. Box 19569|Toronto ON  M4W3T9"

我有这个正则表达式

^(.*\|)*((?i).*(room|st.|street|road|avenue|P.O.|St.).*\|(?-i).*)$

如果字符串中只有一个匹配项,则分组很好。

但如果有不止一次迭代或另一场比赛,它分组 最后一次迭代或最后一次匹配。

例如,对于字符串

"Sleep & Alertness Clinic|790 Bay street |Suite 800| st. 32|Toronto ON  M5G 1N8"

结果是:

  1. 第 1 组。睡眠与警觉诊所|790 Bay street |
  2. 第 2 组。32 街|800 号套房|多伦多 ON M5G 1N8

我想要的是:

  1. 第 1 组。睡眠与警觉诊所|
  2. 第 2 组。790 Bay street |32 st.|Suite 800|Toronto ON M5G 1N8

在regex中,可以在.*后面加一个问号,让它不贪心,第一次匹配就停止

^(.*?(?:room|st\.|street|road|avenue|P\.O\.)[^|]*)(.*)$

Here is a demo

您要查找的表达式可能很简单:

"(.*?)\|(.*)"

您很可能不想要,也不需要锚点 ^$,但如果您出于某种原因需要它们,那么也可以考虑添加其他边界。

正则表达式

您可以 design/modify/change 在 regex101.com 中表达您的表情。

正则表达式电路

您可以在 jex.im 中可视化您的表情:

JavaScript 测试

const regex = /"(.*?)\|(.*)"/gmi;
const str = `"Women's College Hospital|76 Grenville Street|ACTT Clinic 6 East|Toronto ON M5S 1B2"
""
"Health and Wellness Center|University of Toronto|214 College Street, Room 111|Toronto ON M5T 2Z9"
"Royal Health Care Centre|130 Adelaide St. West|Lower Concourse|P.O.Box 92|Toronto ON M5H 3P5"
"Suite 1038|790 Bay Street|P.O. Box 51|Toronto ON M5G 1N8 M5G 1N8"
"P.O. Box 19569|Toronto ON M4W3T9"
"Sleep & Alertness Clinic|790 Bay street |Suite 800| st. 32|Toronto ON M5G 1N8"`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

如果你真的必须在第一组中有管道,你可以简单地将它添加到替换中,或者用另一个捕获组包装它。