2017-03-01 95 views
1

我希望這是一個簡單的問題,但我仍然在圍繞着羣組。正則表達式 - 組,需要[this:andthis] from一個字符串

我有這個字符串:this is some text [propertyFromId:34] and this is more text,我會更喜歡他們。我需要獲取括號內的內容,然後是冒號左側僅包含alpha的文本,冒號右側包含整數。

所以,全場比賽:propertyFromId:34,1組:propertyFromId,第2組:34

這是我的出發點(?<=\[)(.*?)(?=])

回答

0

使用

\[([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 
//   ) 
// 
// )