简体   繁体   English

第一场比赛之前一组

[英]One group before and one group after the first match

I'm new to regex and I'm finding it very confusing. 我是regex的新手,但感到非常困惑。 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\\/|/ 第1组: Lorem ipsum\\/|/

Group 2: dolor sit654 | amet consectetur 第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)(.*)/ 我尝试编写这样的正则表达式,但没有成功:/(. /(.*?)(\\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. 分组中-但是您希望分组2是第二个子字符串,而不是分隔字符。 Either move those outside of a group: 要么将这些移出组:

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

Or use a non-capturing group instead: 或改为使用非捕获组:

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

https://regex101.com/r/v7ZRr1/1 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与正则表达式减去中间捕获组一起使用。 split used this way will leave extraneous empty strings on the ends of the array, but you can filter() these easily with: 这种方式使用split会在数组的末端留下多余的空字符串,但是您可以使用以下方法轻松地filter()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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