2017-03-16 9 views
2

からいくつかの値を取得する:正規表現は、次の入力文字列を有する入力文字列

"health status index    pri rep docs.count docs.deleted store.size pri.store.size 
yellow open first_index   5 1  222173   0  43.8gb   43.8gb 
green open second_index   5 1  27131   7  36.6gb   36.6gb 
red  open third_index   5 1  4047   0  22.4mb   22.4mb 
" 

私は最初の列、healthと3 1、indexをとり、次の出力文字列を、取得できますか?

"first_index - yellow, first_index - green, third_index - red" 

ありがとうございます。

PS:indexの名前は、_indexと異なる場合があります。上記のすべての例は_indexですが、_indexのないインデックスもあります。 statusの値も異なります。中でも

+0

が、これは文字列ではなく配列になる理由はありますか? – Loko

+0

アレイも問題ありません。 –

+0

** **これを配列または文字列として保存する選択肢がある場合は、配列として保存することをお勧めします。これが外部ソースから来て、配列として持つことができない場合は、私を無視してください。 – Loko

答えて

1

、これは動作します:

^(\w+)\W+\w+\W+(\w+) 

テイク・グループ\2\1a demo on regex101.comを参照してください(とMULTILINE修飾子を気)。あなたはその後、捕捉基-2及び捕捉基-1を取ることができる

/^(\S+)\h+\S+\h+(\S+)/m 

<?php 

$string = <<<DATA 
health status index    pri rep docs.count docs.deleted store.size pri.store.size 
yellow open first_index   5 1  222173   0  43.8gb   43.8gb 
green open second_index   5 1  27131   7  36.6gb   36.6gb 
red  open third_index   5 1  4047   0  22.4mb   22.4mb 
DATA; 

$regex = '~^(\w+)\W+\w+\W+(\w+)~m'; 

preg_match_all($regex, $string, $matches, PREG_SET_ORDER); 

foreach ($matches as $match) { 
    echo $match[2] . "-" . $match[1] . "\n"; 
} 
?> 
1

あなたはpreg_match_all関数における2つの捕捉基と、この正規表現を使用することができます。PHPコード(demo on ideone.com)として


あなたの出力をフォーマットする。ここで

RegEx Demo

1

仕事をするための方法である:

$str = "health status index    pri rep docs.count docs.deleted store.size pri.store.size 
yellow open first_index   5 1  222173   0  43.8gb   43.8gb 
green open second_index   5 1  27131   7  36.6gb   36.6gb 
red  open third_index   5 1  4047   0  22.4mb   22.4mb 
"; 

preg_match_all('/\R(\w+)\h+\w+\h+(\w+)/', $str, $m); 
print_r($m); 

出力:

Array 
(
    [0] => Array 
     (
      [0] => 
yellow open first_index 
      [1] => 
green open second_index 
      [2] => 
red  open third_index 
     ) 

    [1] => Array 
     (
      [0] => yellow 
      [1] => green 
      [2] => red 
     ) 

    [2] => Array 
     (
      [0] => first_index 
      [1] => second_index 
      [2] => third_index 
     ) 

) 
関連する問題