正規表現で文字列で合致する部分を全て抜き出し加工した形で表示する

Contents

出力

1=apple
2=orange

説明

この例で使われている正規表現のフラグ
e=プログラム処理を正規表現の中で実行可能(Perlのみ)
g=1回の合致ではなく合致する箇所全て対象にする
i=大文字・小文字を無視
s=Ruby以外の言語で改行を無視するフラグ
m=Rubyで改行を無視するフラグ


JavaScript

const value = `This is target 1.
Name is apple.
Target 2 is here. 
Name is orange.`
if (matches = [...value.matchAll(/target\s([\d+]).*?Name\s+is\s+([^\.]+)\./sig)] ) {
    for (match of matches) {
        console.log(match[1]+"="+match[2]);
    }
}

Perl

my $check_value = $value = "This is target 1.
Name is apple.
Target 2 is here. 
Name is orange.";
$check_value=~ s{target\s([\d+]).*?Name\s+is\s+([^\.]+)\.}{
    print $1.'='.$2."\n";
}gesi;

PHP

<?php
$value = "This is target 1.
Name is apple.
Target 2 is here. 
Name is orange.";
$matches = [];
preg_match_all('/target\s([\d+]).*?Name\s+is\s+([^\.]+)\./is', $value, $matches);
if(isset($matches[1])) {
    $i = 0;
    foreach($matches[1] as $match) {
        print($match."=".$matches[2][$i]."\n");
        $i++;
    }
}

Python

import re
value = """This is target 1.
Name is apple.
Target 2 is here. 
Name is orange."""
matches = re.findall( r'target\s([\d+]).*?Name\s+is\s+([^\.]+)\.', value, re.IGNORECASE | re.DOTALL)
for match in matches:
  print(match[0]+"="+match[1])

Ruby

value = "This is target 1.
Name is apple.
Target 2 is here. 
Name is orange.";
matches = value.scan(/target\s([\d+]).*?Name\s+is\s+([^\.]+)\./im)
for match in matches do
  puts(match[0]+"="+match[1])
end