简体   繁体   中英

One group before and one group after the first match

I'm new to regex and I'm finding it very confusing. I'm having trouble trying to figure out how to separate this string in two groups

Lorem ipsum\/|/ | dolor sit654 | amet consectetur

Group 1: Lorem ipsum\\/|/

Group 2: dolor sit654 | amet consectetur dolor sit654 | amet consectetur

The pattern is the | ("space" + "vertical bar" + "space")

I want to get everything before and after the first match of these characters above each in a group

I've tried writing a regex like this, with no sucess: /(.*?)(\\s\\|\\s)(.*)/

Is this possible?

Your regexp works fine:

let str = 'Lorem ipsum\/|/ | dolor sit654 | amet consectetur';
console.log(str.match(/(.*?)(\s\|\s)(.*)/))

Output:

Array(4) [ "Lorem ipsum/|/ | dolor sit654 | amet consectetur", "Lorem ipsum/|/", " | ", "dolor sit654 | amet consectetur" ]

You could improve it by removing the 2nd capturing group

console.log(str.match(/(.*?)\s\|\s(.*)/))

Output:

Array(3) [ "Lorem ipsum/|/ | dolor sit654 | amet consectetur", "Lorem ipsum/|/", "dolor sit654 | amet consectetur" ]

or making it non-capturing:

console.log(str.match(/(.*?)(?:\s\|\s)(.*)/))

Output:

Array(3) [ "Lorem ipsum/|/ | dolor sit654 | amet consectetur", "Lorem ipsum/|/", "dolor sit654 | amet consectetur" ]

You're currently capturing the initial | in a group - but you want group 2 to be the second substring, not the separating characters. Either move those outside of a group:

(.*?) \| (.*)
     ^^^^

Or use a non-capturing group instead:

(.*?)(?: \| )(.*)
     ^^^^^^^^

https://regex101.com/r/v7ZRr1/1

 console.log( `Lorem ipsum\\/|/ | dolor sit654 | amet consectetur` .match(/(.*?) \\| (.*)/) ); 

You can use split with your regex minus the middle capture group. split used this way will leave extraneous empty strings on the ends of the array, but you can filter() these easily with:

 const str = 'Lorem ipsum\\/|/ | dolor sit654 | amet consectetur' let arr = str.split(/(.*?)\\s\\|\\s(.*)/).filter(s => s) console.log(arr) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM