正则表达式 - 组,需要[this:andthis] from一个字符串

问题描述:

我希望这是一个简单的问题,但我仍然在围绕着群组。正则表达式 - 组,需要[this:andthis] from一个字符串

我有这个字符串:this is some text [propertyFromId:34] and this is more text,我会更喜欢他们。我需要获取括号内的内容,然后是冒号左侧仅包含alpha的文本,冒号右侧包含整数。

所以,全场比赛:propertyFromId:34,1组:propertyFromId,第2组:34

这是我的出发点(?<=\[)(.*?)(?=])

使用

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

regex demo

详情

  • \[ - 一个[符号
  • ([a-zA-Z]+) - 第1组捕获一种或多种α-字符([[:alpha:]]+\p{L}+,可以使用太)
  • : - 冒号
  • (\d+) - 组2捕获一个或多个数字
  • ] - 关闭]符号。

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 
//   ) 
// 
// )