Reputation: 3270
I have this string: title: one description: two
and want to split it into groups like [title: one
, description: two
]
options.match(/(title|description):.+?/gi)
this was my attempt, but it only captures up to the : and 1 space after, it does not include the text after it, which I want to include all of, up until the second match.
Upvotes: 1
Views: 211
Reputation: 4302
var str = "title: one description: two";
/* split with positive lookbehinds . A space must precede by all but : */
var res=str.split(/(?<=[^:])\s/);
console.log(res);
/* match general rule */
var res=str.match(/([^:\s]+:\s[^:\s]+)/gi);
console.log(res);
/* match with spacific words */
var res=str.match(/((title|description)+:\s[^:\s]+)/gi);
console.log(res);
Upvotes: 1
Reputation: 163342
You could also get the matches with a capture group and match the whitespace in between
(\b(?:title|description):.+?)\s*(?=\b(?:title|description):|$)
The pattern matches:
(
Capture group 1
\b(?:title|description):
Match either title:
or description:
and :
.+?
Match 1+ times any char no greedy (lazy))
Close group 1\s*
Match optional whitespace chars(?=
Positive lookahead, assert what is at the right is
\b(?:title|description):|$
Match either title:
or description:
or assert the end of the string for the last item)
Close lookaheadconst regex = /(\b(?:title|description):.+?)\s*(?=\b(?:title|description):|$)/gi;
let s = "title: one description: two";
console.log(Array.from(s.matchAll(regex), m => m[1]));
Upvotes: 1
Reputation: 370729
Split on a lookahead for title
or description
:
const str = 'title: one description: two';
console.log(
str.split(/ (?=title|description)/)
);
Upvotes: 1