简体   繁体   English

使用正则表达式捕获第一部分,跳过中间部分,并捕获最后一部分

[英]Use Regex to capture first part, skip middle, and capture last part

I've some lines like the example below, I want to capture everything in the first bracket, then everything in the some texts part.我有一些像下面的例子一样的行,我想捕获第一个括号中的所有内容,然后是some texts部分中的所有内容。

{Foo} - {Bar} - some texts

Expected result: {Foo} - some texts预期结果: {Foo} - some texts

All the texts and the ones in the brackets will be different, so I will need to based it off on the {} and - to capture what I need.所有文本和括号中的文本都将不同,因此我需要将其基于{}-以捕获我需要的内容。

What I've came up with gets everything in the first bracket, \\{(.*?)\\} .我想出的所有内容都放在第一个括号\\{(.*?)\\} However I'm not too sure how I can skip the middle part and just grab the some texts .但是,我不太确定如何跳过中间部分,只抓取some texts I'm looking at using lookaround assertions, is that the best way to approach this?我正在考虑使用环视断言,这是解决这个问题的最佳方法吗?

Thanks.谢谢。

Use 2 Capture Groups to Exclude the Middle使用 2 个捕获组排除中间

 /(\\{.+?\\})\\s-\\s\\{.+?\\}\\s-\\s(.+?)\\b/gi;

☝ ☝ ☝ ☝
Replace from here to ..........................there with \\s-\\s用 \\s-\\s 替换从这里到......................................那里

This pattern will match multiples on the same line and/or multiple lines.此模式将匹配同一行和/或多行上的倍数。


Demo演示

 var str = `{Foo} - {Bar} - some text {Foo} - {Bar} - some different text {Foo} - {Bar} - this text is always matched correctly because the word boundary at the end {Foo} - {Bar} - so this pattern is ok sharing the same line and/or {Foo} - {Bar} - multiple lines`; var rgx = /(\\{.+?\\})\\s-\\s\\{.+?\\}\\s-\\s(.+?)\\b/gi; var res = str.replace(rgx, '$1 - $2'); console.log(res);

This works in perl, it is skipping everything up to and including .+\\} - then matching whatever is left:这适用于 perl,它跳过所有内容,包括.+\\} -然后匹配剩下的任何内容:

$ cat x.pl
use strict;

my $str = '{Foo} - {Bar} - some texts';

if ($str =~ /\{(.*?)\}.+\} - (.+)/) {
    print "$1, $2\n";
}


$ perl x.pl
Foo, some texts

以下正则表达式应该作为/({[^}]+})(?:.+})?(.+)/与包含{Foo} 的capture group 1capture group 2一些文本

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

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