I have several strings that I want to extract name with regex. The whole name is inside one or more pipes as any other part of the string.
Each string may be blank, some samples:
"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 have this regex
^(.*\|)*((?i).*(room|st.|street|road|avenue|P.O.|St.).*\|(?-i).*)$
It groups well if there is only one match in the string.
But if there is more than one iteration or another match, it groups with the last iteration or last match.
For example, for the string
"Sleep & Alertness Clinic|790 Bay street |Suite 800| st. 32|Toronto ON M5G 1N8"
the result is:
What I want is:
The expression you are looking for may be as simple as:
"(.*?)\|(.*)"
Most likely you don't want, nor need, the anchors ^
and $
, but if you want them for some reason then consider adding other boundaries as well.
You can design/modify/change your expressions in regex101.com.
You can visualize your expressions in jex.im:
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}`);
});
}
If you really have to have the pipe in the first group, you could simply add it in replace, or maybe wrap it with another capturing group.