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

Contents [hide]

出力

1=apple
2=orange

説明

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


JavaScript

1
2
3
4
5
6
7
8
9
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

1
2
3
4
5
6
7
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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

1
2
3
4
5
6
7
8
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

1
2
3
4
5
6
7
8
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

プログラミング言語比較サイトProgrammingLang.comでは、同じ問題を複数のプログラミング言語がそれぞれどのような記述で解決できるのかの例を提供。
複数の言語を比較し、貴方の問題を解決するのに最適な言語の選択と、その言語での解法を得る事を手助けします。
全問題カバー: JavaScript Perl PHP Python Ruby | 一部: C C# C++ Go Java Rust Shell
 
問題解法大分類(50音順)
Class | 時間 | 数値 | System | Database | Test | Network | 配列 | ファイルシステム | 変数 | 文字列
その他役立ちコンテンツ

※当サイトではアフィリエイトプログラムを利用して商品を紹介しています。