简体   繁体   中英

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.

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(/\\[([^:]+):([^:\\]]+)\\]/) ); 

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

\\[([az]+):([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(/\\[([az]+):([a-z0-9]+)]/i)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM