2016-12-16 2 views
0

特定のパターンから数値を抽出しようとしています。パターンを使用して段落から数値を抽出します。

ここには「安定した患者(3787を含む)」という文字列の例があります。

この番号は、「患者」という単語の後、または「ワード」の患者の前の任意の場所に指定できます。特定の単語の前後にある最初の数字セットだけを抽出したいと思います。

これを使用しようとすると、しかし、あなたがキーワードの後に​​番号を見つけるために、2つの正規表現、キーワードの前に番号を見つけるために1、他を使用することができます

function get_numerics ($str) { 
    preg_match('/Patients\s*(\d+)/', $str, $matches); 
    return $matches[0]; 
} 
+0

'\ s *'は空白ですが、間には関係なく患者の後ろの最初の番号を引っぱりますか?また、 'Patients'はサンプル文字列の小文字ですが、正規表現には' i'修飾子が必要です。 '$ matches [0]'は一致し、 '$ matches [1]'は整数になります。 – chris85

+0

数字と患者さんとの関係を説明したり定義しなければならないかもしれないと考えましたか?テキストに年、患者、および多数の患者が含まれていたらどうなりますか? –

+0

数字は文字列のどこにあってもかまいませんか、それとも単語 "patients"のすぐ隣にある必要がありますか? – 4castle

答えて

0

を働いていません。どちらかが見つかった場合は、キーワードと数値の間の距離を文字数で計算します。計算された距離ごとに、キーワードに最も近い数字を返します。おそらく、キーワードと数値の間の最大距離を制限することもできます。あなたのキーワードから数百文字の数字を返すのはあまり意味がありませんよね?下に最大20文字を使用しました。

function get_numerics($str) { 
    $word = 'patients'; 
    preg_match('/(\d+)[^\d]{1,20}?'.$word.'/i', $str, $matches_before); 
    preg_match('/'.$word.'[^\d]{1,20}?(\d+)/i', $str, $matches_after); 
    $distance_before = PHP_INT_MAX; 
    $distance_after = PHP_INT_MAX; 
    if (count($matches_before) == 2) { 
     $distance_before = strlen($matches_before[0]) - strlen($matches_before[1]) - strlen($word); 
    } 
    if (count($matches_after) == 2) { 
     $distance_after = strlen($matches_after[0]) - strlen($matches_after[1]) - strlen($word); 
    } 
    if (count($matches_before) == 2 || count($matches_after) == 2) { 
     if ($distance_before < $distance_after) { 
      return (int) $matches_before[1]; 
     } else { 
      return (int) $matches_after[1]; 
     } 
    } 
    return FALSE; 
} 

var_dump(get_numerics("24 stable patients, including some")); 
// Returns 24 
var_dump(get_numerics("stable patients, including 3787 with")); 
// Returns 3787 
var_dump(get_numerics("24 stable patients, including 3787 with")); 
// Returns 24, because it's the closest from the 'patients' keyword 
var_dump(get_numerics("24 stable blablabla patients, including 3787 with")); 
// Returns 3787, because it's the closest from the 'patients' keyword 
var_dump(get_numerics("stable blablabla patients, including some that are not ok. But 3787 planes ")); 
// Returns FALSE, because 3787 is too far from the 'patients' keyword 
+0

ありがとうございますが、私はこのような "2933人の患者のうち、1948"がある場合、システムは1948年を患者として読みます。 – SamIAm

関連する問題