1

I hope this is a simple question, but I'm still getting my head around groups.

I have this string: this is some text [propertyFromId:34] and this is more text and I will have more like them. I need to get the content between the brackets then a group with the alpha-only text on left of the colon and group with the integer on the right of the colon.

So, full Match: propertyFromId:34, Group 1: propertyFromId, Group 2: 34

This is my starting point (?<=\[)(.*?)(?=])

Warren
  • 1,984
  • 3
  • 29
  • 60

1 Answers1

0

Use

\[([a-zA-Z]+):(\d+)]

See the regex demo

Details:

  • \[ - a [ symbol
  • ([a-zA-Z]+) - Group 1 capturing one or more alpha chars ([[:alpha:]]+ or \p{L}+ can be used, too)
  • : - a colon
  • (\d+) - Group 2 capturing one or more digits
  • ] - a closing ] symbol.

PHP demo:

$re = '~\[([a-zA-Z]+):(\d+)]~';
$str = 'this is some text [propertyFromId:34] and this is more text';
preg_match_all($re, $str, $matches);
print_r($matches);
// => Array
//   (
//       [0] => Array
//           (
//               [0] => [propertyFromId:34]
//           )
//   
//       [1] => Array
//           (
//               [0] => propertyFromId
//           )
//   
//       [2] => Array
//           (
//               [0] => 34
//           )
//   
//   )
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563