Jonathan Stegall
Jonathan Stegall

Reputation: 530

Regex to match string inside square brackets, separated by colon

I'm trying to parse a string that always has the format: [firstpart:lastpart] in such a way that I can get "firstpart" and "lastpart" as separate items. The "firstpart" value is always a string, and the "lastpart" value could contain integers and text. The whole string [firstpart:lastpart] could be surrounded by any amount of other text that I don't need, hence the brackets.

I've been trying to modify this:

([^:\s]+):([^:\s]+)

As is, it gets me this:

  1. [firstpart:lastpart
  2. [firstpart
  3. lastpart]

So it's just that I need to remove the open and close brackets from 2 and 3.

Is this possible with just a regex? I'm using JavaScript in a TinyMCE plugin, in case that is relevant.

Upvotes: 0

Views: 787

Answers (2)

The fourth bird
The fourth bird

Reputation: 163362

You could match the opening and the closing bracket outside of the group:

\[([a-z]+):([a-z0-9]+)]

Note that [^:\s]+ Matches not a colon or a whitespace character which matches more than a string or a string or integers and escape the opening \[ to match it literally or else it would start a character class.

let str = "[firstpart:lastpart]";
console.log(str.match(/\[([a-z]+):([a-z0-9]+)]/i));

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370819

Put \[ and \] at the beginning and end of the regular expression, respectively, and capture the text between them:

console.log(
  'foo[firstpart:lastpart]bar'.match(/\[([^:]+):([^:\]]+)\]/)
);

Upvotes: 3

Related Questions