提问者:小点点

JavaScript:Regexp搜索并提取“{}”中的字符串


这就是我要搜索的字符串。

Make {The Most|One of the most} Out Of Your {Real Estate|Realty|Property} {Purchase|Acquisition} When You {Follow|Comply With|Adhere To} { something } These Tips

它应该搜索并返回用花括号{}括起来的字符串的部分,并且其中必须包含一个或多个管道符号。

下面是我想出的regexp,但它不起作用。

/^{?([^{]*\|)*}$

预期产出

[{The Most|One of the most}, {Real Estate|Realty|Property}, {Real Estate|Realty|Property}, {Purchase|Acquisition}, {Follow|Comply With|Adhere To}]

注意,{something}不应该是输出的一部分。 提前致谢


共2个答案

匿名用户

您可以使用2个否定字符类,确保匹配至少1次管道。

{[^{}|\n]+\|[^{}\n]*}

解释

  • {匹配{
  • [^{}\n]+匹配除{}或换行
  • 以外的任何字符
  • \Mat ch
  • [^{}\n]*匹配0+次任何字符,{}或换行(也允许另一个)
  • 除外
  • }匹配}

正则表达式演示

null

const regex = /{[^{}|\n]+\|[^{}\n]*}/g;
const str = `Make {The Most|One of the most} Out Of Your {Real Estate|Realty|Property} {Purchase|Acquisition} When You {Follow|Comply With|Adhere To} { something } These Tips`;
console.log(str.match(regex));

匿名用户

您可以使用正向前瞻来匹配管道,如下所示:

null

const str = `Make {The Most|One of the most} Out Of Your {Real Estate|Realty|Property} {Purchase|Acquisition} When {|} You {Follow|Comply With|Adhere To} { something } These Tips
`;

const result = str.match(/{.*?(?=\|)[^}]*}+/g);

console.log(result)