这是我要搜索的字符串。
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
它应该搜索并返回包含在大括号 { }
中的字符串部分,并且其中必须包含一个或多个竖线 |
符号。
以下是我想出的正则表达式,但它不起作用。
/^{?([^{]*\|)*}$
预期输出
[{The Most|One of the most}, {Real Estate|Realty|Property}, {Real Estate|Realty|Property}, {Purchase|Acquisition}, {Follow|Comply With|Adhere To}]
请注意,{ something }
不应该是输出的一部分。
提前致谢
最佳答案
您可以使用 2 个否定字符类,确保至少匹配 1 次竖线。
如果应该至少有一个字符(请注意,这也可以是一个空格),您可以将量词更改为 +
{[^{}|]*\|[^{}]*}
解释
{
匹配{
[^{}|\n]*
匹配 0+ 次除{
}
,|
之外的任何字符> 或换行符\|
匹配|
[^{}\n]*
匹配 0+ 次除{
或}
或换行符之外的任何字符(这也允许另一个|
)匹配
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));
如果在管道之前和之后必须有一个除 |
{
和 }
之外的非空白字符:
{[^\S\n]*[^\s{}|][^{}|]*\|[^\S\n]*[^\s{}|][^{}]*}
解释
{
匹配开头{
[^\S\n]*
匹配除换行符外的 0+ 个空白字符[^\s{}|]
匹配除{
}
或|
以外的非空白字符[^{}|]*
匹配 0+ 次除{
}
或|
以外的任何字符\|
匹配|
[^\S\n]*
匹配除换行符外的 0+ 个空白字符[^\s{}|]
匹配除{
}
或|
以外的非空白字符[^{}]*
匹配 0+ 次除{
}
或|
以外的任何字符/li>匹配结束
关于Javascript:正则表达式搜索并提取 "{ }"内的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62578239/