stackers
stackers

Reputation: 3270

Regex match any characters in string, up until next match

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

Answers (3)

Mohammed Elhag
Mohammed Elhag

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

The fourth bird
The fourth bird

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 lookahead

Regex demo

const 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

CertainPerformance
CertainPerformance

Reputation: 370729

Split on a lookahead for title or description:

const str = 'title: one description: two';
console.log(
  str.split(/ (?=title|description)/)
);

Upvotes: 1

Related Questions