Reputation: 778
This is the string I want to search in.
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
It should search for and return parts of strings that are enclosed in curly braces { }
and must contain one or more pipe |
symbol inside them.
Following is the regexp I came up with but it doesn't work.
/^{?([^{]*\|)*}$
Expected Output
[{The Most|One of the most}, {Real Estate|Realty|Property}, {Real Estate|Realty|Property}, {Purchase|Acquisition}, {Follow|Comply With|Adhere To}]
Note that { something }
shouldn't be a part of the output.
Thanks in advance
Upvotes: 2
Views: 98
Reputation: 32158
You can use positive lookahead to match the pipe |
like this:
const str = `Make {The Most|One of the most} Out {klm} 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)
Upvotes: 2
Reputation: 163217
You might use 2 negated character classes, making sure to match at least 1 times a pipe.
You could change the quantifier to +
if there should be at least a single char (note that this could also be a single space)
{[^{}|]*\|[^{}]*}
Explanation
{
Match {
[^{}|\n]*
Match 0+ times any char except {
}
, |
or newline\|
Match |
[^{}\n]*
Match 0+ times any char except {
or }
or newline (which allows also another |
)}
Match }
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));
If there has to be a non whitespace char other that |
{
and }
before and after the pipe:
{[^\S\n]*[^\s{}|][^{}|]*\|[^\S\n]*[^\s{}|][^{}]*}
Explanation
{
Match opening {
[^\S\n]*
Match 0+ whitespace chars except a newline[^\s{}|]
Match a non whitespace char other than {
}
or |
[^{}|]*
Match 0+ times any char other than {
}
or |
\|
Match |
[^\S\n]*
Match 0+ whitespace chars except a newline[^\s{}|]
Match a non whitespace char other than {
}
or |
[^{}]*
Match 0+ times any char other than {
}
or |
}
Match closing }
Upvotes: 5