プログラミング言語の比較 > 基本的な処理

複数行の文字列リテラル

Java

Java 15以降
  1. String s = """
  2. 1行目
  3. 2行目
  4. 3行目
  5. """;
Java 14まで
  1. String s = "1行目\n"
  2. + "2行目\n"
  3. + "3行目";

Groovy

  1. def s = '''1行目
  2. 2行目
  3. 3行目'''
  1. def s = /1行目\
  2. 2行目\
  3. 3行目/

Kotlin

  1. val s = """1行目
  2. 2行目
  3. 3行目"""

Scala

  1. val s = """1行目
  2. 2行目
  3. 3行目"""
  1. val s = """|1行目
  2. |2行目
  3. |3行目""".stripMargin // 各行の先頭の余白を削る

Erlang

  1. S = "1行目
  2. 2行目
  3. 3行目".

Haskell

  1. let s = unlines ["1行目",
  2. "2行目",
  3. "3行目"]

PowerShell

  1. $s = @'
  2. 1行目
  3. 2行目
  4. 3行目
  5. '@

F#

  1. let s = "1行目
  2. 2行目
  3. 3行目"

C#

  1. string s = @"1行目
  2. 2行目
  3. 3行目";

C++

  1. string s = "";
  2. s += "1行目\n";
  3. s += "2行目\n";
  4. s += "3行目";

Go

  1. s := `1行目
  2. 2行目
  3. 3行目`

Rust

  1. let s = "1行目
  2. 2行目
  3. 3行目";

Dart

  1. var s = '''1行目
  2. 2行目
  3. 3行目''';

TypeScript

  1. let s = `1行目
  2. 2行目
  3. 3行目`;

JavaScript

  1. let s = `1行目
  2. 2行目
  3. 3行目`;

CoffeeScript

  1. s = '''
  2. 1行目
  3. 2行目
  4. 3行目
  5. '''

Ruby

  1. s = '1行目
  2. 2行目
  3. 3行目'
  1. s = <<~'END'
  2. 1行目
  3. 2行目
  4. 3行目
  5. END

Python

  1. s = '''1行目
  2. 2行目
  3. 3行目'''

PHP

  1. $s = '1行目
  2. 2行目
  3. 3行目';
  1. $s = <<<'END'
  2. 1行目
  3. 2行目
  4. 3行目
  5. END;

Perl

  1. my $s = '1行目
  2. 2行目
  3. 3行目';
  1. my $s = <<'END';
  2. 1行目
  3. 2行目
  4. 3行目
  5. END

文字列中に変数の値を埋め込む(printf など)

Java

printf 方式
  1. String name = "Taro";
  2. int age = 20;
  3. String s = String.format("He is %s. %s is %d years old.", name, name, age);
  1. String name = "Taro";
  2. int age = 20;
  3. String s = String.format("He is %1$s. %1$s is %2$d years old.", name, age); // 1:name 2:age
printf 方式
Java 13以降
  1. String name = "Taro";
  2. int age = 20;
  3. String s = "He is %s. %s is %d years old.".formatted(name, name, age);
  1. String name = "Taro";
  2. int age = 20;
  3. String s = "He is %1$s. %1$s is %2$d years old.".formatted(name, age); // 1:name 2:age
インデックス指定方式
  1. // import java.text.MessageFormat;
  2. String name = "Taro";
  3. int age = 20;
  4. String s = MessageFormat.format("He is {0}. {0} is {1} years old.", name, age); // 0:name 1:age
Commons Text を使った場合
キー指定方式
  1. // import org.apache.commons.text.StringSubstitutor;
  2. Map<String, Object> map = Map.of(
  3. "name", "Taro",
  4. "age", 20);
  5. String s = new StringSubstitutor(map).replace("He is ${name}. ${name} is ${age} years old.");

Groovy

式展開方式
  1. def name = 'Taro'
  2. def age = 20
  3. def s = "He is $name. $name is $age years old."
  1. def map = [name: 'Taro', age: 20]
  2. def s = "He is ${map.name}. ${map.name} is ${map.age} years old."
printf 方式
  1. def name = 'Taro'
  2. def age = 20
  3. def s = String.format('He is %s. %s is %d years old.', name, name, age)
  1. def name = 'Taro'
  2. def age = 20
  3. def s = String.format('He is %1$s. %1$s is %2$d years old.', name, age) // 1:name 2:age
インデックス指定方式
  1. // import java.text.MessageFormat
  2. def name = 'Taro'
  3. def age = 20
  4. def s = MessageFormat.format("He is {0}. {0} is {1} years old.", name, age) // 0:name 1:age
キー指定方式
  1. def map = [name: 'Taro', age: 20]
  2. def s = map.with { "He is ${name}. ${name} is ${age} years old." }

Kotlin

式展開方式
  1. val name = "Taro"
  2. val age = 20
  3. val s = "He is $name. $name is $age years old."
printf 方式
  1. val name = "Taro"
  2. val age = 20
  3. val s = "He is %s. %s is %d years old.".format(name, name, age)
  1. val name = "Taro"
  2. val age = 20
  3. val s = "He is %1$s. %1$s is %2$d years old.".format(name, age) // 1:name 2:age
インデックス指定方式
  1. // import java.text.MessageFormat
  2. val name = "Taro"
  3. val age = 20
  4. val s = MessageFormat.format("He is {0}. {0} is {1} years old.", name, age) // 0:name 1:age

Scala

式展開方式
  1. val name = "Taro"
  2. val age = 20
  3. val s = s"He is ${name}. ${name} is ${age} years old."
  1. val name = "Taro"
  2. val age = 20
  3. val s = f"He is ${name}%s. ${name}%s is ${age}%d years old."
printf 方式
  1. val name = "Taro"
  2. val age = 20
  3. val s = "He is %s. %s is %d years old.".format(name, name, age)
  1. val name = "Taro"
  2. val age = 20
  3. val s = format("He is %s. %s is %d years old.", name, name, age)
  1. val name = "Taro"
  2. val age = 20
  3. val s = "He is %1$s. %1$s is %2$d years old.".format(name, age) // 1:name 2:age
  1. val name = "Taro"
  2. val age = 20
  3. val s = format("He is %1$s. %1$s is %2$d years old.", name, age) // 1:name 2:age
インデックス指定方式
  1. // import java.text.MessageFormat
  2. val name = "Taro"
  3. val age = 20
  4. val s = MessageFormat.format("He is {0}. {0} is {1} years old.", name, age) // 0:name 1:age

Erlang

printf 方式
  1. S = io:format("He is ~s. ~s is ~p years old.", ["Taro", "Taro", 20]).

Haskell

printf 方式
  1. -- import Text.Printf
  2. let name = "Taro"
  3. let age = 20
  4. let s = printf "He is %s. %s is %d years old." name name (age :: Int) :: String

PowerShell

インデックス指定方式
  1. $name = 'Taro'
  2. $age = 20
  3. $s = 'He is {0}. {0} is {1} years old.' -f $name, $age # 0:name 1:age

F#

式展開方式
F# 5.0以降
  1. let name = "Taro"
  2. let age = 20
  3. let s = $"He is {name}. {name} is {age} years old."
printf 方式
  1. let name = "Taro"
  2. let age = 20
  3. let s = sprintf "He is %s. %s is %d years old." name name age
インデックス指定方式
  1. let name = "Taro"
  2. let age = 20
  3. let s = System.String.Format("He is {0}. {0} is {1} years old.", name, age) // 0:name 1:age
キー指定方式風
  1. // open System.Collections.Generic
  2. // open System.Text.RegularExpressions
  3. let format pattern (dict : IDictionary<_, _>) =
  4. Regex.Replace(pattern, @"\$(\w+)", fun (m : Match) -> string dict.[m.Groups.[1].Value])
  5. let d = dict [("name", box "Taro"); ("age", box 20)] // d の型は IDictionary<string, obj>
  6. let s = format "He is $name. $name is $age years old." d

C#

式展開方式
  1. string name = "Taro";
  2. int age = 20;
  3. string s = $"He is {name}. {name} is {age} years old.";
インデックス指定方式
  1. string name = "Taro";
  2. int age = 20;
  3. string s = string.Format("He is {0}. {0} is {1} years old.", name, age); // 0:name 1:age
キー指定方式風
  1. // using System.Text.RegularExpressions;
  2. public static string Format<T>(string pattern, IDictionary<string, T> dict) {
  3. return Regex.Replace(pattern, @"\$(\w+)", m => dict[m.Groups[1].Value].ToString());
  4. }
  1. var dict = new Dictionary<string, object> { { "name", "Taro" }, { "age", 20 } };
  2. string s = Format("He is $name. $name is $age years old.", dict);

C++

printf 方式
  1. #include <cstdio>
  2. char* name = "Taro";
  3. int age = 20;
  4. const int N = 256; // 十分なサイズを見積もっておく
  5. char buf[N];
  6. snprintf(buf, N, "He is %s. %s is %d years old.", name, name, age);
  7. string s(buf);
Boost を使った場合
printf 方式
  1. #include <boost/format.hpp>
  2. string name = "Taro";
  3. int age = 20;
  4. string s = (boost::format("He is %s. %s is %d years old.") % name % name % age).str();
  1. #include <boost/format.hpp>
  2. string name = "Taro";
  3. int age = 20;
  4. string s = (boost::format("He is %1$s. %1$s is %2$d years old.") % name % age).str(); // 1:name 2:age
インデックス指定方式
  1. #include <boost/format.hpp>
  2. string name = "Taro";
  3. int age = 20;
  4. string s = (boost::format("He is %1%. %1% is %2% years old.") % name % age).str(); // 1:name 2:age

Go

printf 方式
  1. name := "Taro"
  2. age := 20
  3. s := fmt.Sprintf("He is %s. %s is %d years old.", name, name, age)

Rust

  1. let name = "Taro";
  2. let age = 20;
  3. let s = format!("He is {}. {} is {} years old.", name, name, age);
インデックス指定方式
  1. let name = "Taro";
  2. let age = 20;
  3. let s = format!("He is {0}. {0} is {1} years old.", name, age);
式展開方式
  1. let name = "Taro";
  2. let age = 20;
  3. let s = format!("He is {name}. {name} is {age} years old.");
キー指定方式
  1. let s = format!("He is {name}. {name} is {age} years old.", name = "Taro", age = 20);

Dart

式展開方式
  1. var name = 'Taro';
  2. var age = 20;
  3. var s = 'He is $name. $name is $age years old.';

TypeScript

式展開方式
  1. let name = 'Taro';
  2. let age = 20;
  3. let s = `He is ${name}. ${name} is ${age} years old.`;
Node.js の場合
printf 方式
  1. // import * as util from 'util';
  2. let name = 'Taro';
  3. let age = 20;
  4. let s = util.format('He is %s. %s is %d years old.', name, name, age);

JavaScript

式展開方式
  1. let name = 'Taro';
  2. let age = 20;
  3. let s = `He is ${name}. ${name} is ${age} years old.`;
Node.js の場合
printf 方式
  1. // const util = require('util');
  2. let name = 'Taro';
  3. let age = 20;
  4. let s = util.format('He is %s. %s is %d years old.', name, name, age);

CoffeeScript

式展開方式
  1. name = 'Taro'
  2. age = 20
  3. s = "He is #{name}. #{name} is #{age} years old."
Node.js の場合
printf 方式
  1. # util = require 'util'
  2. name = 'Taro'
  3. age = 20
  4. s = util.format 'He is %s. %s is %d years old.', name, name, age

Ruby

式展開方式
  1. name = 'Taro'
  2. age = 20
  3. s = "He is #{name}. #{name} is #{age} years old."
printf 方式
  1. name = 'Taro'
  2. age = 20
  3. s = 'He is %s. %s is %d years old.' % [name, name, age]
  1. name = 'Taro'
  2. age = 20
  3. s = 'He is %1$s. %1$s is %2$d years old.' % [name, age] # 1:name 2:age
  1. name = 'Taro'
  2. age = 20
  3. s = sprintf 'He is %s. %s is %d years old.', name, name, age
  1. name = 'Taro'
  2. age = 20
  3. s = sprintf 'He is %1$s. %1$s is %2$d years old.', name, age # 1:name 2:age
インデックス指定方式風
  1. s = 'He is %{0}. %{0} is %{1} years old.' % {'0': 'Taro', '1': 20}
  1. def indexed_hash *args
  2. args.each_with_index.to_h {|item, index| [index.to_s.to_sym, item] }
  3. end
  4. s = 'He is %{0}. %{0} is %{1} years old.' % indexed_hash('Taro', 20)
キー指定方式
  1. s = 'He is %{name}. %{name} is %{age} years old.' % {name: 'Taro', age: 20}
  1. s = sprintf 'He is %{name}. %{name} is %{age} years old.', name: 'Taro', age: 20

Python

式展開方式
  1. name = 'Taro'
  2. age = 20
  3. s = f'He is {name}. {name} is {age} years old.'
printf 方式
  1. name = 'Taro'
  2. age = 20
  3. s = 'He is %s. %s is %d years old.' % (name, name, age)
printf+キー指定方式
  1. d = {'name': 'Taro', 'age': 20}
  2. s = 'He is %(name)s. %(name)s is %(age)d years old.' % d
インデックス指定方式
  1. name = 'Taro'
  2. age = 20
  3. s = 'He is {0}. {0} is {1} years old.'.format(name, age) # 0:name 1:age
キー指定方式
  1. s = 'He is {name}. {name} is {age} years old.'.format(name = 'Taro', age = 20)
  1. d = {'name': 'Taro', 'age': 20}
  2. s = 'He is {name}. {name} is {age} years old.'.format(**d)
  1. # import string
  2. d = {'name': 'Taro', 'age': 20}
  3. s = string.Template('He is $name. $name is $age years old.').substitute(d)
  1. # import string
  2. s = string.Template('He is $name. $name is $age years old.').substitute(name = 'Taro', age = 20)

PHP

式展開方式
  1. $name = 'Taro';
  2. $age = 20;
  3. $s = "He is $name. $name is $age years old.";
  1. $array = ['name' => 'Taro', 'age' => 20];
  2. $s = "He is {$array['name']}. {$array['name']} is {$array['age']} years old.";
printf 方式
  1. $name = 'Taro';
  2. $age = 20;
  3. $s = sprintf('He is %s. %s is %d years old.', $name, $name, $age);

Perl

式展開方式
  1. my $name = 'Taro';
  2. my $age = 20;
  3. my $s = "He is $name. $name is $age years old.";
  1. my %hash = (name => 'Taro', age => 20);
  2. my $s = "He is $hash{name}. $hash{name} is $hash{age} years old.";
printf 方式
  1. my $name = 'Taro';
  2. my $age = 20;
  3. my $s = sprintf 'He is %s. %s is %d years old.', $name, $name, $age;
  1. my $name = 'Taro';
  2. my $age = 20;
  3. my $s = sprintf 'He is %1$s. %1$s is %2$d years old.', $name, $age; # 1:name 2:age
CPAN の String::Formatter を使った場合
キー指定方式
  1. # use String::Formatter;
  2. my $fmt = String::Formatter->new({
  3. input_processor => 'require_named_input',
  4. string_replacer => 'named_replace',
  5. codes => {s => sub { $_ }}
  6. });
  7. my %hash = (name => 'Taro', age => 20);
  8. my $s = $fmt->format('He is %{name}s. %{name}s is %{age}s years old.', \%hash);

同じ文字列を繰り返す

「Yes!Yes!Yes!」という文字列を作る。

Java

  1. String s = "Yes!".repeat(3);

Groovy

  1. def s = 'Yes!' * 3

Kotlin

  1. val s = "Yes!".repeat(3)

Scala

  1. val s = "Yes!" * 3

Erlang

  1. S = lists:flatten(lists:duplicate(3, "Yes!")).

Haskell

  1. let s = concat $ take 3 $ repeat "Yes!"
  1. let s = concatMap (const "Yes!") [1..3]

PowerShell

  1. $s = 'Yes!' * 3

F#

  1. let s = String.replicate 3 "Yes!"

C#

  1. string s = string.Join("Yes!", new string[3 + 1]); // 4つの空文字列を "Yes!" で連結する

C++

  1. #include <sstream>
  2. stringstream ss;
  3. for (int i = 0; i < 3; i++) {
  4. ss << "Yes!";
  5. }
  6. string s = ss.str();

Go

  1. // import "strings"
  2. s := strings.Repeat("Yes!", 3)

Rust

  1. let s = "Yes!".repeat(3);

Dart

  1. var sb = new StringBuffer();
  2. for (var i = 0; i < 3; i++) {
  3. sb.write('Yes!');
  4. }
  5. var s = sb.toString();

TypeScript

  1. let s = 'Yes!'.repeat(3);

JavaScript

  1. let s = 'Yes!'.repeat(3);

CoffeeScript

  1. s = 'Yes!'.repeat(3)

Ruby

  1. s = 'Yes!' * 3

Python

  1. s = 'Yes!' * 3

PHP

  1. $s = str_repeat('Yes!', 3);

Perl

  1. my $s = 'Yes!' x 3;

文字列中の文字の並びを逆にする

Java

  1. String s = new StringBuilder("ABCDE").reverse().toString();
Commons Lang を使った場合
  1. // import org.apache.commons.lang3.StringUtils;
  2. String s = StringUtils.reverse("ABCDE");

Groovy

  1. def s = 'ABCDE'.reverse()
  1. def s = 'ABCDE'[-1..0] // 0 は文字列の先頭、-1 は末尾を表す

Kotlin

  1. val s = "ABCDE".reversed()

Scala

  1. var s = "ABCDE".toCharArray.reverse.mkString

Erlang

  1. S = lists:reverse("ABCDE").

Haskell

  1. let s = reverse "ABCDE"

PowerShell

  1. $chars = 'ABCDE'.ToCharArray()
  2. [Array]::Reverse($chars)
  3. $s = New-Object string (,$chars)

F#

  1. let s = new string("ABCDE".ToCharArray() |> Array.rev)

C#

  1. string s = new string("ABCDE".Reverse().ToArray());

C++

  1. string s = "ABCDE";
  2. reverse(s.begin(), s.end()); // s の内容が変わる

Go

  1. // import "bytes"
  2. // import "strings"
  3. chars := strings.Split("ABCDE", "")
  4. buf := bytes.NewBufferString("")
  5. for i := len(chars) - 1; i >= 0; i-- {
  6. buf.WriteString(chars[i])
  7. }
  8. s := buf.String()

Rust

  1. let s = "ABCDE".chars().rev().collect::<String>();

Dart

  1. var chars = 'ABCDE'.split('');
  2. var sb = new StringBuffer();
  3. for (var i = chars.length; i > 0; ) {
  4. i--;
  5. sb.write(chars[i]);
  6. }
  7. String s = sb.toString();

TypeScript

  1. let s = 'ABCDE'.split('').reverse().join('');

JavaScript

  1. let s = 'ABCDE'.split('').reverse().join('');

CoffeeScript

  1. s = 'ABCDE'.split('').reverse().join ''

Ruby

  1. s = 'ABCDE'.reverse

Python

  1. s = ''.join(reversed('ABCDE'))

PHP

  1. $s = strrev('ABCDE');

Perl

  1. my $s = join '', reverse(split //, 'ABCDE');

正規表現を使って、日付を表す文字列から年・月・日を取り出す

Java

  1. // import java.util.regex.*;
  2. Pattern p = Pattern.compile("^(\\d{4})-(\\d{1,2})-(\\d{1,2})$");
  3. Matcher m = p.matcher("2010-01-03");
  4. if (m.matches()) {
  5. String year = m.group(1);
  6. String month = m.group(2);
  7. String day = m.group(3);
  8. ...
  9. }
グループ名を付ける
  1. // import java.util.regex.*;
  2. Pattern p = Pattern.compile("^(?<year>\\d{4})-(?<month>\\d{1,2})-(?<day>\\d{1,2})$");
  3. Matcher m = p.matcher("2010-01-03");
  4. if (m.matches()) {
  5. String year = m.group("year");
  6. String month = m.group("month");
  7. String day = m.group("day");
  8. ...
  9. }

Groovy

  1. def m = '2010-01-03' =~ /^(\d{4})-(\d{1,2})-(\d{1,2})$/
  2. if (m.matches()) {
  3. def (_, year, month, day) = m[0]
  4. ...
  5. }
  1. def p = ~ /^(\d{4})-(\d{1,2})-(\d{1,2})$/ // p の型は java.util.regex.Pattern
  2. '2010-01-03'.find(p) { _, year, month, day ->
  3. ...
  4. }
グループ名を付ける
  1. def m = '2010-01-03' =~ /^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$/
  2. if (m.matches()) {
  3. def year = m.group('year')
  4. def month = m.group('month')
  5. def day = m.group('day')
  6. ...
  7. }

Kotlin

  1. val re = Regex("""(\d{4})-(\d{1,2})-(\d{1,2})""")
  2. val m = re.matchEntire("2010-01-03")
  3. if (m != null) {
  4. val (year, month, day) = m.destructured
  5. ...
  6. }

Scala

  1. val re = """^(\d{4})-(\d{1,2})-(\d{1,2})$""".r // re の型は scala.util.matching.Regex
  2. val re(year, month, day) = "2010-01-03" // パターンマッチ。マッチしなかった場合は例外が起きる
  1. val re = """^(\d{4})-(\d{1,2})-(\d{1,2})$""".r // re の型は scala.util.matching.Regex
  2. "2010-01-03" match {
  3. case re(year, month, day) => ... // マッチした場合
  4. case _ => // マッチしなかった場合は何もしない
  5. }
グループ名を付ける
  1. // import java.util.regex.Pattern
  2. val p = Pattern.compile("""^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$""")
  3. val m = p.matcher("2010-01-03")
  4. if (m.matches) {
  5. val year = m.group("year")
  6. val month = m.group("month")
  7. val day = m.group("day")
  8. ...
  9. }
Scala 3.0以降
  1. // import java.util.regex.Pattern
  2. val p = Pattern.compile("""^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$""")
  3. val m = p.matcher("2010-01-03")
  4. if m.matches then
  5. val year = m.group("year")
  6. val month = m.group("month")
  7. val day = m.group("day")
  8. ...

Erlang

  1. RE = "^(\\d{4})-(\\d{1,2})-(\\d{1,2})$",
  2. %% パターンマッチ。マッチしなかった場合は例外が起きる
  3. {match, [_, Year, Month, Day]} = re:run("2010-01-03", RE, [{capture, all, list}]).
グループ名を付ける
  1. RE = "^(?<year>\\d{4})-(?<month>\\d{1,2})-(?<day>\\d{1,2})$",
  2. %% パターンマッチ。マッチしなかった場合は例外が起きる
  3. {match, [Year, Month, Day]} = re:run("2010-01-03", RE, [{capture, [year, month, day], list}]).

Haskell

  1. -- import Text.Regex
  2. let regex = mkRegex "^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})$"
  3. -- パターンマッチ。マッチしなかった場合は例外が起きる
  4. let Just [year, month, day] = matchRegex regex "2010-01-03"
  1. -- import Text.Regex
  2. -- import Text.Regex.Posix
  3. let pattern = "([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})"
  4. -- パターンマッチ。マッチしなかった場合は例外が起きる
  5. let ("", _, "", [year, month, day]) = "2010-01-03" =~ pattern :: (String, String, String, [String])

PowerShell

  1. if ('2010-01-03' -match '^(\d{4})-(\d{1,2})-(\d{1,2})$') {
  2. $year, $month, $day = $Matches[1], $Matches[2], $Matches[3]
  3. ...
  4. }
  1. if ('2010-01-03' -match '^(\d{4})-(\d{1,2})-(\d{1,2})$') {
  2. $year, $month, $day = @(1..3) | foreach { $Matches[$_] }
  3. ...
  4. }
グループ名を付ける
  1. if ('2010-01-03' -match '^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$') {
  2. $year, $month, $day = $Matches.year, $Matches.month, $Matches.day
  3. ...
  4. }
  1. if ('2010-01-03' -match '^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$') {
  2. $year, $month, $day = echo year month day | foreach { $Matches[$_] } # echo は配列を作るコマンド
  3. ...
  4. }

F#

  1. // open System.Text.RegularExpressions
  2. let m = Regex.Match("2010-01-03", @"^(\d{4})-(\d{1,2})-(\d{1,2})$")
  3. match [for g in m.Groups -> g.Value] with
  4. | [_; year; month; day] -> ... // マッチした場合
  5. | _ -> // マッチしなかった場合は何もしない
  1. // open System.Text.RegularExpressions
  2. let (|Groups|_|) (m : Match) =
  3. if m.Success then Some [for g in m.Groups -> g.Value] else None
  4. match Regex.Match("2010-01-03", @"^(\d{4})-(\d{1,2})-(\d{1,2})$") with
  5. | Groups [_; year; month; day] -> ... // マッチした場合
  6. | _ -> // マッチしなかった場合は何もしない
  1. // open System.Text.RegularExpressions
  2. let (|RE|_|) pattern input =
  3. let m = Regex.Match(input, pattern)
  4. if m.Success then Some [for g in m.Groups -> g.Value] else None
  5. match "2010-01-03" with
  6. | RE @"^(\d{4})-(\d{1,2})-(\d{1,2})$" [_; year; month; day] -> ... // マッチした場合
  7. | _ -> // マッチしなかった場合は何もしない
グループ名を付ける
  1. // open System.Text.RegularExpressions
  2. let m = Regex.Match("2010-01-03", @"^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$")
  3. match [for name in ["year"; "month"; "day"] -> m.Groups.[name].Value] with
  4. | [year; month; day] -> ... // マッチした場合
  5. | _ -> // マッチしなかった場合は何もしない
  1. // open System.Text.RegularExpressions
  2. let (|Groups|_|) (m : Match, names : seq<string>) =
  3. if m.Success then Some [for name in names -> m.Groups.[name].Value] else None
  4. let m = Regex.Match("2010-01-03", @"^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$")
  5. match m, ["year"; "month"; "day"] with
  6. | Groups [year; month; day] -> ... // マッチした場合
  7. | _ -> () // マッチしなかった場合は何もしない

C#

  1. // using System.Text.RegularExpressions;
  2. Match m = Regex.Match("2010-01-03", @"^(\d{4})-(\d{1,2})-(\d{1,2})$");
  3. if (m.Success) {
  4. string year = m.Groups[1].Value;
  5. string month = m.Groups[2].Value;
  6. string day = m.Groups[3].Value;
  7. ...
  8. }
グループ名を付ける
  1. // using System.Text.RegularExpressions;
  2. Match m = Regex.Match("2010-01-03", @"^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$");
  3. if (m.Success) {
  4. string year = m.Groups["year"].Value;
  5. string month = m.Groups["month"].Value;
  6. string day = m.Groups["day"].Value;
  7. ...
  8. }

C++

Boost を使った場合
  1. #include <boost/regex.hpp>
  2. boost::regex r("^(\\d{4})-(\\d{1,2})-(\\d{1,2})$");
  3. boost::smatch m;
  4. if (boost::regex_search(string("2010-01-03"), m, r)) {
  5. string year = m.str(1);
  6. string month = m.str(2);
  7. string day = m.str(3);
  8. ...
  9. }

Go

  1. // import "regexp"
  2. r := regexp.MustCompile(`^(\d{4})-(\d{1,2})-(\d{1,2})$`)
  3. result := r.FindStringSubmatch("2010-01-03")
  4. if len(result) > 0 {
  5. year, month, day := result[1], result[2], result[3]
  6. ...
  7. }

Rust

regex を使った場合
  1. // use regex::Regex;
  2. let re = Regex::new(r"(\d{4})-(\d{1,2})-(\d{1,2})").unwrap();
  3. match re.captures("2010-01-03") {
  4. Some(caps) => {
  5. let year = &caps[1];
  6. let month = &caps[2];
  7. let day = &caps[3];
  8. ...
  9. },
  10. }
グループ名を付ける
  1. // use regex::Regex;
  2. let re = Regex::new(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})").unwrap();
  3. match re.captures("2010-01-03") {
  4. Some(caps) => {
  5. let year = &caps["year"];
  6. let month = &caps["month"];
  7. let day = &caps["day"];
  8. ...
  9. },
  10. }

Dart

  1. var m = RegExp(r'^(\d{4})-(\d{1,2})-(\d{1,2})$').firstMatch('2010-01-03');
  2. if (m != null) {
  3. var year = m[1]!;
  4. var month = m[2]!;
  5. var day = m[3]!;
  6. ...
  7. }
グループ名を付ける
  1. var m = RegExp(r'^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$').firstMatch('2010-01-03');
  2. if (m != null) {
  3. var year = m.namedGroup('year')!;
  4. var month = m.namedGroup('month')!;
  5. var day = m.namedGroup('day')!;
  6. ...
  7. }

TypeScript

  1. let m = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec('2010-01-03');
  2. if (m) {
  3. let [, year, month, day] = m;
  4. ...
  5. }
グループ名を付ける
  1. let m = /^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$/.exec('2010-01-03');
  2. if (m) {
  3. let { year, month, day } = m.groups!;
  4. ...
  5. }

JavaScript

  1. let m = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec('2010-01-03');
  2. if (m) {
  3. let [, year, month, day] = m;
  4. ...
  5. }
グループ名を付ける
  1. let m = /^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$/.exec('2010-01-03');
  2. if (m) {
  3. let { year, month, day } = m.groups;
  4. ...
  5. }

CoffeeScript

  1. m = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec '2010-01-03'
  2. if m
  3. [, year, month, day] = m
  4. ...
グループ名を付ける
  1. m = /^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$/.exec '2010-01-03'
  2. if m
  3. { year, month, day } = m.groups
  4. ...

Ruby

  1. if '2010-01-03' =~ /^(\d{4})-(\d{1,2})-(\d{1,2})$/ # String =~ Regexp
  2. year, month, day = $1, $2, $3
  3. ...
  4. end
  1. if /^(\d{4})-(\d{1,2})-(\d{1,2})$/ =~ '2010-01-03' # Regexp =~ String
  2. year, month, day = $~[1..3]
  3. ...
  4. end
  1. if /^(\d{4})-(\d{1,2})-(\d{1,2})$/ === '2010-01-03' # Regexp === String
  2. year, month, day = Regexp.last_match[1..3]
  3. ...
  4. end
  1. if '2010-01-03'[/^(\d{4})-(\d{1,2})-(\d{1,2})$/] # String[Regexp]
  2. year, month, day = $~.captures
  3. ...
  4. end
  1. if m = '2010-01-03'.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/) # String.match(Regexp)
  2. year, month, day = m[1..3]
  3. ...
  4. end
  1. if m = '2010-01-03'.match('^(\d{4})-(\d{1,2})-(\d{1,2})$') # String.match(String)
  2. year, month, day = m.captures
  3. ...
  4. end
  1. if m = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.match('2010-01-03') # Regexp.match(String)
  2. year, month, day = m.values_at 1, 2, 3
  3. ...
  4. end
グループ名を付ける
  1. if '2010-01-03' =~ /^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$/ # String =~ Regexp
  2. year, month, day = $~[:year], $~[:month], $~[:day]
  3. ...
  4. end
  1. if m = '2010-01-03'.match(/^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$/) # String.match(Regexp)
  2. year, month, day = m[:year], m[:month], m[:day]
  3. ...
  4. end

Python

  1. # import re
  2. m = re.compile(r'^(\d{4})-(\d{1,2})-(\d{1,2})$').search('2010-01-03')
  3. if m:
  4. year, month, day = m.groups()
グループ名を付ける
  1. # import re
  2. m = re.compile(r'^(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$').search('2010-01-03')
  3. if m:
  4. year = m.group('year')
  5. month = m.group('month')
  6. day = m.group('day')
  1. # import re
  2. m = re.compile(r'^(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$').search('2010-01-03')
  3. if m:
  4. year, month, day = map(m.group, ('year', 'month', 'day'))

PHP

  1. if (mb_ereg('^(\d{4})-(\d{1,2})-(\d{1,2})$', '2010-01-03', $m)) {
  2. list(, $year, $month, $day) = $m;
  3. ...
  4. }
PHP 7.1以降
  1. if (mb_ereg('^(\d{4})-(\d{1,2})-(\d{1,2})$', '2010-01-03', $m)) {
  2. [, $year, $month, $day] = $m;
  3. ...
  4. }
PHP 7.3以降
  1. if (mb_ereg('^(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})$', '2010-01-03', $m)) {
  2. ['year' => $year, 'month' => $month, 'day' => $day] = $m;
  3. ...
  4. }

Perl

  1. if ('2010-01-03' =~ /^(\d{4})-(\d{1,2})-(\d{1,2})$/) {
  2. my ($year, $month, $day) = ($1, $2, $3);
  3. ...
  4. }
  1. my ($year, $month, $day) = ('2010-01-03' =~ /^(\d{4})-(\d{1,2})-(\d{1,2})$/);
  2. if (defined $year) {
  3. ...
  4. }

正規表現を使って、日付を表す文字列を全て抜き出す

Java

  1. // import java.util.regex.*;
  2. // import java.util.stream.Stream;
  3. String s = "2010-1-3 から 2010-12-31 まで";
  4. Matcher matcher = Pattern.compile("\\d{4}-\\d{1,2}-\\d{1,2}").matcher(s);
  5. Stream<String> dates = matcher.results().map(mr -> mr.group());

Groovy

  1. def s = '2010-1-3 から 2010-12-31 まで'
  2. def dates = s.findAll(/\d{4}-\d{1,2}-\d{1,2}/)

Kotlin

  1. val s = "2010-1-3 から 2010-12-31 まで"
  2. val re = Regex("""\d{4}-\d{1,2}-\d{1,2}""")
  3. val dates = re.findAll(s).map { it.value }

Scala

  1. var s = "2010-1-3 から 2010-12-31 まで"
  2. val re = """\d{4}-\d{1,2}-\d{1,2}""".r // r の型は scala.util.matching.Regex
  3. val dates = re.findAllIn(s) // dates の型は scala.util.matching.Regex.MatchIterator

Erlang

  1. S = "2010-1-3 から 2010-12-31 まで",
  2. {match, Captured} = re:run(S, "\\d{4}-\\d{1,2}-\\d{1,2}", [global, {capture, first, list}]),
  3. Dates = [Date || [Date] <- Captured]. %% Captured は“文字列のリストのリスト”なので、“文字列のリスト”に変換する

Haskell

  1. -- import Text.Regex
  2. findAll regex s =
  3. case matchRegexAll regex s of
  4. Just (_, matched, suffix, _) -> matched : findAll regex suffix
  5. otherwise -> []
  1. -- import List
  2. -- import Text.Regex
  3. findAll regex = unfoldr $ \ s ->
  4. case matchRegexAll regex s of
  5. Just (_, matched, suffix, _) -> Just (matched, suffix)
  6. otherwise -> Nothing
  1. let s = "2010-1-3 から 2010-12-31 まで"
  2. let regex = mkRegex "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}"
  3. let dates = findAll regex s

PowerShell

  1. $s = '2010-1-3 から 2010-12-31 まで'
  2. $dates = ([Regex] '\d{4}-\d{1,2}-\d{1,2}').Matches($s) | foreach { $_.Value }

F#

  1. // open System.Text.RegularExpressions
  2. let s = "2010-1-3 から 2010-12-31 まで"
  3. let r = new Regex @"\d{4}-\d{1,2}-\d{1,2}"
  4. let dates = [for m in r.Matches s -> m.Value]

C#

  1. // using System.Linq;
  2. // using System.Text.RegularExpressions;
  3. var s = "2010-1-3 から 2010-12-31 まで";
  4. var r = new Regex(@"\d{4}-\d{1,2}-\d{1,2}");
  5. var dates = r.Matches(s).Cast<Match>().Select(m => m.Value); // dates の型は IEnumerable<string>

C++

  1. #include <vector>
  2. #include <boost/regex.hpp>
  3. struct push_to_vector {
  4. vector<string>& v;
  5. push_to_vector(vector<string>& v) : v(v) { }
  6. bool operator()(const boost::match_results<string::const_iterator>& m) {
  7. v.push_back(m.str(0));
  8. return true;
  9. }
  10. };
  1. string s = "2010-1-3 から 2010-12-31 まで";
  2. boost::regex r("\\d{4}-\\d{1,2}-\\d{1,2}");
  3. vector<string> dates;
  4. boost::regex_grep(push_to_vector(dates), s, r);

Go

  1. // import "regexp"
  2. r := regexp.MustCompile(`\d{4}-\d{1,2}-\d{1,2}`)
  3. dates := r.FindAllString("2010-1-3 から 2010-12-31 まで", -1) // dates の型は []string

Rust

regex を使った場合
  1. // use regex::Regex;
  2. let s = "2010-1-3 から 2010-12-31 まで";
  3. let re = Regex::new(r"\d{4}-\d{1,2}-\d{1,2}").unwrap();
  4. let dates: Vec<_> = re.captures_iter(s).map(|caps| String::from(&caps[0])).collect();

Dart

  1. var s = '2010-1-3 から 2010-12-31 まで';
  2. var matches = RegExp(r'\d{4}-\d{1,2}-\d{1,2}').allMatches(s);
  3. var dates = [];
  4. for (var m in matches) {
  5. dates.add(m[0]);
  6. }

TypeScript

  1. let s = '2010-1-3 から 2010-12-31 まで';
  2. let dates = s.match(/\d{4}-\d{1,2}-\d{1,2}/g);

JavaScript

  1. let s = '2010-1-3 から 2010-12-31 まで';
  2. let dates = s.match(/\d{4}-\d{1,2}-\d{1,2}/g);

CoffeeScript

  1. s = '2010-1-3 から 2010-12-31 まで'
  2. dates = s.match /\d{4}-\d{1,2}-\d{1,2}/g

Ruby

  1. s = '2010-1-3 から 2010-12-31 まで'
  2. dates = s.scan /\d{4}-\d{1,2}-\d{1,2}/

Python

  1. # import re
  2. s = '2010-1-3 から 2010-12-31 まで'
  3. dates = re.compile(r'\d{4}-\d{1,2}-\d{1,2}').findall(s)
  1. # import re
  2. s = '2010-1-3 から 2010-12-31 まで'
  3. dates = re.findall(r'\d{4}-\d{1,2}-\d{1,2}', s)

PHP

  1. $s = '2010-1-3 から 2010-12-31 まで';
  2. $dates = [];
  3. mb_ereg_search_init($s, '\d{4}-\d{1,2}-\d{1,2}');
  4. while (list($date) = mb_ereg_search_regs()) {
  5. array_push($dates, $date);
  6. }
PHP 7.1以降
  1. $s = '2010-1-3 から 2010-12-31 まで';
  2. $dates = [];
  3. mb_ereg_search_init($s, '\d{4}-\d{1,2}-\d{1,2}');
  4. while ([$date] = mb_ereg_search_regs()) {
  5. array_push($dates, $date);
  6. }

Perl

  1. my $s = '2010-1-3 から 2010-12-31 まで';
  2. my @dates = $s =~ /\d{4}-\d{1,2}-\d{1,2}/g;

正規表現を使って、日付を表す文字列の区切りを全てハイフンからスラッシュに置き換える

Java

  1. String s = "2010-1-3 から 2010-12-31 まで";
  2. s = s.replaceAll("(\\d{4})-(\\d{1,2})-(\\d{1,2})", "$1/$2/$3");
  1. // import java.util.regex.Pattern;
  2. String s = "2010-1-3 から 2010-12-31 まで";
  3. Pattern p = Pattern.compile("(\\d{4})-(\\d{1,2})-(\\d{1,2})");
  4. s = p.matcher(s).replaceAll("$1/$2/$3");
式を使って置換する
  1. // import java.util.regex.*;
  2. String s = "2010-1-3 から 2010-12-31 まで";
  3. Matcher m = Pattern.compile("(\\d{4})-(\\d{1,2})-(\\d{1,2})").matcher(s);
  4. s = m.replaceAll(mr -> mr.group(1) + "/" + mr.group(2) + "/" + mr.group(3))
グループ名を付ける
  1. String s = "2010-1-3 から 2010-12-31 まで";
  2. s = s.replaceAll("(?<year>\\d{4})-(?<month>\\d{1,2})-(?<day>\\d{1,2})", "${year}/${month}/${day}");
  1. // import java.util.regex.Pattern;
  2. String s = "2010-1-3 から 2010-12-31 まで";
  3. Pattern p = Pattern.compile("(?<year>\\d{4})-(?<month>\\d{1,2})-(?<day>\\d{1,2})");
  4. s = p.matcher(s).replaceAll("${year}/${month}/${day}");
グループ名を付け、式を使って置換する
  1. // import java.util.regex.*;
  2. String s = "2010-1-3 から 2010-12-31 まで";
  3. Matcher m = Pattern.compile("(?<year>\\d{4})-(?<month>\\d{1,2})-(?<day>\\d{1,2})").matcher(s);
  4. s = m.replaceAll(mr -> mr.group("year") + "/" + mr.group("month") + "/" + mr.group("day"));

Groovy

  1. def s = '2010-1-3 から 2010-12-31 まで'
  2. s = s.replaceAll(/(\d{4})-(\d{1,2})-(\d{1,2})/, '$1/$2/$3')
  1. def s = '2010-1-3 から 2010-12-31 まで'
  2. s = (~ /(\d{4})-(\d{1,2})-(\d{1,2})/).matcher(s).replaceAll('$1/$2/$3')
式を使って置換する
  1. def s = '2010-1-3 から 2010-12-31 まで'
  2. s = s.replaceAll(/(\d{4})-(\d{1,2})-(\d{1,2})/) { _, year, month, day -> "$year/$month/$day" }
グループ名を付ける
  1. def s = '2010-1-3 から 2010-12-31 まで'
  2. s = s.replaceAll(/(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})/, '${year}/${month}/${day}')
グループ名を付け、式を使って置換する
  1. def s = '2010-1-3 から 2010-12-31 まで'
  2. def m = (~ /(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})/).matcher(s)
  3. s = m.replaceAll { "${it.group('year')}/${it.group('month')}/${it.group('day')}" as String }

Kotlin

  1. var s = "2010-1-3 から 2010-12-31 まで"
  2. val re = Regex("""(\d{4})-(\d{1,2})-(\d{1,2})""")
  3. s = re.replace(s, "$1/$2/$3")
式を使って置換する
  1. var s = "2010-1-3 から 2010-12-31 まで"
  2. val re = Regex("""(\d{4})-(\d{1,2})-(\d{1,2})""")
  3. s = re.replace(s) {
  4. val (year, month, day) = it.destructured
  5. "$year/$month/$day"
  6. }
グループ名を付ける
  1. var s = "2010-1-3 から 2010-12-31 まで"
  2. val re = Regex("""(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})""")
  3. s = re.replace(s, "\${year}/\${month}/\${day}")

Scala

  1. var s = "2010-1-3 から 2010-12-31 まで"
  2. s = """(\d{4})-(\d{1,2})-(\d{1,2})""".r.replaceAllIn(s, "$1/$2/$3")
式を使って置換する
  1. var s = "2010-1-3 から 2010-12-31 まで"
  2. s = """(\d{4})-(\d{1,2})-(\d{1,2})""".r.replaceAllIn(s, m => "%s/%s/%s".format(m.subgroups: _*))
  1. // import scala.util.matching.Regex.Groups
  2. var s = "2010-1-3 から 2010-12-31 まで"
  3. s = """(\d{4})-(\d{1,2})-(\d{1,2})""".r.replaceAllIn(s,
  4. _ match { case Groups(year, month, day) => "%s/%s/%s".format(year, month, day) })
グループ名を付ける
  1. var s = "2010-1-3 から 2010-12-31 まで"
  2. s = """(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})""".r.replaceAllIn(s, "${year}/${month}/${day}")
グループ名を付け、式を使って置換する
  1. var s = "2010-1-3 から 2010-12-31 まで"
  2. s = """(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})""".r.replaceAllIn(s, m => s"${m.group("year")}/${m.group("month")}/${m.group("day")}")

Erlang

  1. S = "2010-1-3 から 2010-12-31 まで",
  2. Result = re:replace(S, "(\\d{4})-(\\d{1,2})-(\\d{1,2})", "\\1/\\2/\\3", [global, {return, list}]).

Haskell

式を使って置換する
  1. -- import Text.Regex
  2. replaceAll regex s f =
  3. case matchRegexAll regex s of
  4. Just (prefix, _, suffix, groups) -> prefix ++ f groups ++ replaceAll regex suffix f
  5. otherwise -> s
  1. let s = "2010-1-3 から 2010-12-31 まで"
  2. let regex = mkRegex "([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})"
  3. let result = replaceAll regex s $ \ [year, month, day] -> year ++ "/" ++ month ++ "/" ++ day

PowerShell

  1. $s = '2010-1-3 から 2010-12-31 まで'
  2. $s = $s -replace '(\d{4})-(\d{1,2})-(\d{1,2})', '$1/$2/$3'
  1. $s = '2010-1-3 から 2010-12-31 まで'
  2. $s = ([Regex] '(\d{4})-(\d{1,2})-(\d{1,2})').Replace($s, '$1/$2/$3')
式を使って置換する
  1. $s = '2010-1-3 から 2010-12-31 まで'
  2. $s = ([Regex] '(\d{4})-(\d{1,2})-(\d{1,2})').Replace($s, { '{1}/{2}/{3}' -f ([string[]] $args[0].Groups) })
グループ名を付ける
  1. $s = '2010-1-3 から 2010-12-31 まで'
  2. $s = ([Regex] '(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})').Replace($s, '${year}/${month}/${day}')
グループ名を付け、式を使って置換する
  1. $s = '2010-1-3 から 2010-12-31 まで'
  2. $s = ([Regex] '(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})').Replace($s, {
  3. param($m)
  4. '{0}/{1}/{2}' -f (echo year month day | foreach { $m.Groups[$_] }) # echo は配列を作るコマンド
  5. })

F#

  1. // open System.Text.RegularExpressions
  2. let mutable s = "2010-1-3 から 2010-12-31 まで"
  3. s <- (new Regex @"(\d{4})-(\d{1,2})-(\d{1,2})").Replace(s, "$1/$2/$3")
式を使って置換する
  1. // open System.Text.RegularExpressions
  2. let format pattern (m : Match) = System.String.Format(pattern, [| for g in m.Groups -> box g |])
  3. let mutable s = "2010-1-3 から 2010-12-31 まで"
  4. s <- (new Regex @"(\d{4})-(\d{1,2})-(\d{1,2})").Replace(s, format "{1}/{2}/{3}")
グループ名を付ける
  1. // open System.Text.RegularExpressions
  2. let mutable s = "2010-1-3 から 2010-12-31 まで"
  3. s <- (new Regex @"(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})").Replace(s, "${year}/${month}/${day}")
グループ名を付け、式を使って置換する
  1. // open System.Text.RegularExpressions
  2. let format pattern (m : Match) =
  3. let f (n : Match) = m.Groups.[n.Groups.[1].Value].Value
  4. (new Regex @"\{(\w+)}").Replace(pattern, f)
  5. let mutable s = "2010-1-3 から 2010-12-31 まで"
  6. s <- (new Regex @"(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})").Replace(s, format "{year}/{month}/{day}")

C#

  1. // using System.Text.RegularExpressions;
  2. string s = "2010-1-3 から 2010-12-31 まで";
  3. s = new Regex(@"(\d{4})-(\d{1,2})-(\d{1,2})").Replace(s, "$1/$2/$3");
式を使って置換する
  1. // using System.Text.RegularExpressions;
  2. string s = "2010-1-3 から 2010-12-31 まで";
  3. s = new Regex(@"(\d{4})-(\d{1,2})-(\d{1,2})").Replace(s, m => m.Result("$1/$2/$3"));
グループ名を付ける
  1. // using System.Text.RegularExpressions;
  2. string s = "2010-1-3 から 2010-12-31 まで";
  3. s = new Regex(@"(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})").Replace(s, "${year}/${month}/${day}");
グループ名を付け、式を使って置換する
  1. // using System.Text.RegularExpressions;
  2. string s = "2010-1-3 から 2010-12-31 まで";
  3. s = new Regex(@"(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})").Replace(s, m => m.Result("${year}/${month}/${day}"));

C++

Boost を使った場合
  1. #include <boost/regex.hpp>
  2. boost::regex r("(\\d{4})-(\\d{1,2})-(\\d{1,2})");
  3. string s = "2010-1-3 から 2010-12-31 まで";
  4. s = boost::regex_replace(s, r, "$1/$2/$3", boost::format_all);

Go

式を使って置換する
  1. // import "regexp"
  2. // import "strings"
  3. s := "2010-1-3 から 2010-12-31 まで"
  4. r := regexp.MustCompile(`\d{4}-\d{1,2}-\d{1,2}`)
  5. s = r.ReplaceAllStringFunc(s, func(matched string) string {
  6. return strings.Replace(matched, "-", "/", -1) // matched には "2010-1-3" などが渡される
  7. })
グループを使い、式を使って置換する
(「$1」などが使えないので、それに代わる関数を用意する)
  1. // import "regexp"
  2. func ReplaceAllStringSubmatchFunc(re *regexp.Regexp, src string, repl func([]string) string) string {
  3. result := ""
  4. for {
  5. indexes := re.FindStringSubmatchIndex(src)
  6. if len(indexes) == 0 {
  7. result += src
  8. break
  9. }
  10. groupCount := len(indexes) / 2
  11. groups := make([]string, groupCount)
  12. for i := 0; i < groupCount; i++ {
  13. groups[i] = src[indexes[i * 2]:indexes[i * 2 + 1]]
  14. }
  15. result += src[:indexes[0]] + repl(groups)
  16. src = src[indexes[1]:]
  17. }
  18. return result
  19. }
  1. s := "2010-1-3 から 2010-12-31 まで"
  2. r := regexp.MustCompile(`(\d{4})-(\d{1,2})-(\d{1,2})`)
  3. s := ReplaceAllStringSubmatchFunc(r, s, func(groups []string) string {
  4. return groups[1] + "/" + groups[2] + "/" + groups[3] // groups には {"2010-1-3", "2010", "1", "3"} などが渡される
  5. })

Rust

regex を使った場合
  1. // use regex::Regex;
  2. let s = "2010-1-3 から 2010-12-31 まで";
  3. let re = Regex::new(r"(\d{4})-(\d{1,2})-(\d{1,2})").unwrap();
  4. let result = re.replace_all(s, "$1/$2/$3");
式を使って置換する
  1. // use regex::*;
  2. let s = "2010-1-3 から 2010-12-31 まで";
  3. let re = Regex::new(r"(\d{4})-(\d{1,2})-(\d{1,2})").unwrap();
  4. let result = re.replace_all(s, |caps: &Captures| { format!("{}/{}/{}", &caps[1], &caps[2], &caps[3]) });
グループ名を付ける
  1. // use regex::Regex;
  2. let s = "2010-1-3 から 2010-12-31 まで";
  3. let re = Regex::new(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})").unwrap();
  4. let result = re.replace_all(s, "${year}/${month}/${day}");
グループ名を付け、式を使って置換する
  1. // use regex::*;
  2. let s = "2010-1-3 から 2010-12-31 まで";
  3. let re = Regex::new(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})").unwrap();
  4. let result = re.replace_all(s, |caps: &Captures| { format!("{year}/{month}/{day}", year = &caps["year"], month = &caps["month"], day = &caps["day"]) });

Dart

式を使って置換する
  1. var s = '2010-1-3 から 2010-12-31 まで';
  2. s = s.replaceAllMapped(RegExp(r'(\d{4})-(\d{1,2})-(\d{1,2})'), (m) => "${m[1]}/${m[2]}/${m[3]}");
グループ名を付け、式を使って置換する
  1. var s = '2010-1-3 から 2010-12-31 まで';
  2. s = s.replaceAllMapped(RegExp(r'(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})'), (m) {
  3. var rem = m as RegExpMatch;
  4. return "${rem.namedGroup('year')}/${rem.namedGroup('month')}/${rem.namedGroup('day')}";
  5. });

TypeScript

  1. let s = '2010-1-3 から 2010-12-31 まで';
  2. s = s.replace(/(\d{4})-(\d{1,2})-(\d{1,2})/g, '$1/$2/$3');
式を使って置換する
  1. let s = '2010-1-3 から 2010-12-31 まで';
  2. s = s.replace(/(\d{4})-(\d{1,2})-(\d{1,2})/g, (_, year, month, day) => `${year}/${month}/${day}`);

JavaScript

  1. let s = '2010-1-3 から 2010-12-31 まで';
  2. s = s.replace(/(\d{4})-(\d{1,2})-(\d{1,2})/g, '$1/$2/$3');
式を使って置換する
  1. let s = '2010-1-3 から 2010-12-31 まで';
  2. s = s.replace(/(\d{4})-(\d{1,2})-(\d{1,2})/g, (_, year, month, day) => `${year}/${month}/${day}`);

CoffeeScript

  1. s = '2010-1-3 から 2010-12-31 まで'
  2. s = s.replace /(\d{4})-(\d{1,2})-(\d{1,2})/g, '$1/$2/$3'
式を使って置換する
  1. s = '2010-1-3 から 2010-12-31 まで'
  2. s = s.replace /(\d{4})-(\d{1,2})-(\d{1,2})/g, (_, year, month, day) -> "#{year}/#{month}/#{day}"

Ruby

  1. s = '2010-1-3 から 2010-12-31 まで'
  2. s.gsub! /(\d{4})-(\d{1,2})-(\d{1,2})/, '\1/\2/\3'
式を使って置換する
  1. s = '2010-1-3 から 2010-12-31 まで'
  2. s.gsub!(/(\d{4})-(\d{1,2})-(\d{1,2})/) { "#{$1}/#{$2}/#{$3}" }
  1. s = '2010-1-3 から 2010-12-31 まで'
  2. s.gsub!(/(\d{4})-(\d{1,2})-(\d{1,2})/) { '%s/%s/%s' % $~.captures }
グループ名を付け、式を使って置換する
  1. s = '2010-1-3 から 2010-12-31 まで'
  2. s.gsub!(/(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})/) { "#{$~[:year]}/#{$~[:month]}/#{$~[:day]}" }
  1. s = '2010-1-3 から 2010-12-31 まで'
  2. s.gsub!(/(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})/) { '%{year}/%{month}/%{day}' % $~.named_captures.transform_keys(&:to_sym) }
  1. # $~.foo の形で $~[:foo] を取り出せるようにする
  2. class MatchData
  3. def method_missing name, *args
  4. self[name]
  5. end
  6. end
  7. s = '2010-1-3 から 2010-12-31 まで'
  8. s.gsub!(/(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})/) { $~.instance_eval { "#{year}/#{month}/#{day}" } }

Python

  1. # import re
  2. s = '2010-1-3 から 2010-12-31 まで'
  3. r = re.compile(r'(\d{4})-(\d{1,2})-(\d{1,2})')
  4. s = r.sub(r'\1/\2/\3', s)
式を使って置換する
  1. # import re
  2. s = '2010-1-3 から 2010-12-31 まで'
  3. r = re.compile(r'(\d{4})-(\d{1,2})-(\d{1,2})')
  4. s = r.sub(lambda m: '%s/%s/%s' % m.groups(), s)
グループ名を付ける
  1. # import re
  2. s = '2010-1-3 から 2010-12-31 まで'
  3. r = re.compile(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})')
  4. s = r.sub(r'\g<year>/\g<month>/\g<day>', s)
グループ名を付け、式を使って置換する
  1. # import re
  2. s = '2010-1-3 から 2010-12-31 まで'
  3. r = re.compile(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})')
  4. def format(template):
  5. return lambda match: template.format(**match.groupdict())
  6. s = r.sub(format('{year}/{month}/{day}'), s)
  1. # import re
  2. # import string
  3. s = '2010-1-3 から 2010-12-31 まで'
  4. r = re.compile(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})')
  5. def format(template):
  6. return lambda match: string.Template(template).substitute(match.groupdict())
  7. s = r.sub(format('$year/$month/$day'), s)

PHP

  1. $s = '2010-1-3 から 2010-12-31 まで';
  2. $s = mb_ereg_replace('(\d{4})-(\d{1,2})-(\d{1,2})', '\1/\2/\3', $s);
式を使って置換する
  1. $s = '2010-1-3 から 2010-12-31 まで';
  2. $s = mb_ereg_replace_callback('(\d{4})-(\d{1,2})-(\d{1,2})', function($m) { return "$m[1]/$m[2]/$m[3]"; }, $s);
式を使って置換する
PHP 7.4以降
  1. $s = '2010-1-3 から 2010-12-31 まで';
  2. $s = mb_ereg_replace_callback('(\d{4})-(\d{1,2})-(\d{1,2})', fn($m) => "$m[1]/$m[2]/$m[3]", $s);
グループ名を付ける
PHP 7.3以降
  1. $s = '2010-1-3 から 2010-12-31 まで';
  2. $s = mb_ereg_replace('(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})', '\k<year>/\k<month>/\k<day>', $s);
グループ名を付け、式を使って置換する
PHP 7.3以降
  1. $s = '2010-1-3 から 2010-12-31 まで';
  2. $s = mb_ereg_replace_callback('(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})', function($m) { return "$m[year]/$m[month]/$m[day]"; }, $s);
グループ名を付け、式を使って置換する
PHP 7.4以降
  1. $s = '2010-1-3 から 2010-12-31 まで';
  2. $s = mb_ereg_replace_callback('(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})', fn($m) => "$m[year]/$m[month]/$m[day]", $s);

Perl

  1. my $s = '2010-1-3 から 2010-12-31 まで';
  2. $s =~ s|(\d{4})-(\d{1,2})-(\d{1,2})|\1/\2/\3|g;
式を使って置換する
  1. my $s = '2010-1-3 から 2010-12-31 まで';
  2. $s =~ s|(\d{4})-(\d{1,2})-(\d{1,2})|sprintf '%s/%s/%s', $1, $2, $3|eg;

文字列の値に応じた数値を変数に代入する(多分岐)

Java

Java 14以降
  1. String s = "zero";
  2. int x = switch (s) {
  3. case "Positive", "positive" -> 1;
  4. case "Negative", "negative" -> -1;
  5. default -> 0;
  6. };
Java 13まで
  1. String s = "zero";
  2. int x;
  3. switch (s) {
  4. case "Positive":
  5. case "positive":
  6. x = 1;
  7. break;
  8. case "Negative":
  9. case "negative":
  10. x = -1;
  11. break;
  12. default:
  13. x = 0;
  14. }

Groovy

  1. def s = 'zero'
  2. def x = s == 'Positive' || s == 'positive' ? 1 :
  3. s == 'Negative' || s == 'negative' ? -1 : 0
  1. def s = 'zero'
  2. def x
  3. switch (s) {
  4. case ['Positive', 'positive']:
  5. x = 1
  6. break
  7. case ['Negative', 'negative']:
  8. x = -1
  9. break
  10. default:
  11. x = 0
  12. }

Kotlin

  1. val s = "zero"
  2. val x = when (s) {
  3. "Positive", "positive" -> 1
  4. "Negative", "negative" -> -1
  5. else -> 0
  6. }

Scala

  1. val s = "zero"
  2. val x = if (s == "Positive" || s == "positive") 1 else
  3. if (s == "Negative" || s == "negative") -1 else 0
  1. val s = "zero"
  2. val x = s match {
  3. case "Positive" | "positive" => 1
  4. case "Negative" | "negative" => -1
  5. case _ => 0
  6. }

Erlang

  1. S = "zero",
  2. X = if
  3. (S =:= "Positive") orelse (S =:= "positive") -> 1;
  4. (S =:= "Negative") orelse (S =:= "negative") -> -1;
  5. true -> 0
  6. end.
  1. S = "zero",
  2. X = case S of
  3. "Positive" -> 1;
  4. "positive" -> 1;
  5. "Negative" -> -1;
  6. "negative" -> -1;
  7. _ -> 0
  8. end.

Haskell

  1. let s = "zero"
  2. let x = case s of
  3. "Positive" -> 1
  4. "positive" -> 1
  5. "Negative" -> -1
  6. "negative" -> -1
  7. _ -> 0

PowerShell

  1. $s = 'zero'
  2. $x = switch -c ($s) { # -c は大文字・小文字を区別するオプション
  3. 'Positive' { 1 }
  4. 'positive' { 1 }
  5. 'Negative' { -1 }
  6. 'negative' { -1 }
  7. default { 0 }
  8. }

F#

  1. let s = "zero"
  2. let x = match s with
  3. | "Positive" | "positive" -> 1
  4. | "Negative" | "negative" -> -1
  5. | _ -> 0
  1. let s = "zero"
  2. let x = s |> function
  3. | "Positive" | "positive" -> 1
  4. | "Negative" | "negative" -> -1
  5. | _ -> 0

C#

C# 9.0以降
  1. string s = "zero";
  2. int x = s switch {
  3. "Positive" or "positive" => 1,
  4. "Negative" or "negative" => -1,
  5. _ => 0
  6. };
C# 8.0以降
  1. string s = "zero";
  2. int x = s switch {
  3. "Positive" => 1,
  4. "positive" => 1,
  5. "Negative" => -1,
  6. "negative" => -1,
  7. _ => 0
  8. };

C++

  1. string s = "zero";
  2. int x = s == "Positive" || s == "positive" ? 1 :
  3. s == "Negative" || s == "negative" ? -1 : 0;

Go

  1. s := "zero"
  2. var x int
  3. switch s {
  4. case "Positive", "positive": x = 1
  5. case "Negative", "negative": x = -1
  6. default: x = 0
  7. }

Rust

  1. let s = "zero";
  2. let x = match s {
  3. "Positive" | "positive" => 1,
  4. "Negative" | "negative" => -1,
  5. _ => 0,
  6. };

Dart

Dart 3.0以降
  1. var s = 'zero';
  2. var x = switch (s) {
  3. 'Positive' || 'positive' => 1,
  4. 'Negative' || 'negative' => -1,
  5. _ => 0,
  6. };

TypeScript

  1. let s = 'zero';
  2. let x = s == 'Positive' || s == 'positive' ? 1 :
  3. s == 'Negative' || s == 'negative' ? -1 : 0;
  1. let s = 'zero';
  2. let x: number;
  3. switch (s) {
  4. case 'Positive':
  5. case 'positive':
  6. x = 1;
  7. break;
  8. case 'Negative':
  9. case 'negative':
  10. x = -1;
  11. break;
  12. default:
  13. x = 0;
  14. }

JavaScript

  1. let s = 'zero';
  2. let x = s == 'Positive' || s == 'positive' ? 1 :
  3. s == 'Negative' || s == 'negative' ? -1 : 0;
  1. let s = 'zero';
  2. let x;
  3. switch (s) {
  4. case 'Positive':
  5. case 'positive':
  6. x = 1;
  7. break;
  8. case 'Negative':
  9. case 'negative':
  10. x = -1;
  11. break;
  12. default:
  13. x = 0;
  14. }

CoffeeScript

  1. s = 'zero'
  2. x = if s == 'Positive' || s == 'positive' then 1 else
  3. if s == 'Negative' || s == 'negative' then -1 else 0
  1. s = 'zero'
  2. x = switch s
  3. when 'Positive', 'positive' then 1
  4. when 'Negative', 'negative' then -1
  5. else 0

Ruby

  1. s = 'zero'
  2. x = s == 'Positive' || s == 'positive' ? 1 :
  3. s == 'Negative' || s == 'negative' ? -1 : 0
  1. s = 'zero'
  2. x = case s
  3. when 'Positive', 'positive' then 1
  4. when 'Negative', 'negative' then -1
  5. else 0
  6. end

Python

  1. s = 'zero'
  2. x = ( 1 if s == 'Positive' || s == 'positive' else
  3. -1 if s == 'Negative' || s == 'negative' else 0)
  1. s = 'zero'
  2. if s == 'Positive' || s == 'positive': x = 1
  3. elif s == 'Negative' || s == 'negative': x = -1
  4. else: x = 0

PHP

  1. $s = 'zero';
  2. $x = $s === 'Positive' || $s === 'positive' ? 1 :
  3. ($s === 'Negative' || $s === 'negative' ? -1 : 0); // 括弧が必須
  1. $s = 'zero';
  2. switch ($s) {
  3. case 'Positive':
  4. case 'positive':
  5. $x = 1;
  6. break;
  7. case 'Negative':
  8. case 'negative':
  9. $x = -1;
  10. break;
  11. default:
  12. $x = 0;
  13. }
PHP 8.0以降
  1. $s = 'zero';
  2. $x = match ($s) {
  3. 'Positive', 'positive' => 1,
  4. 'Negative', 'negative' => -1,
  5. default => 0,
  6. };

Perl

  1. my $s = 'zero';
  2. my $x = $s eq 'Positive' || $s eq 'positive' ? 1 :
  3. $s eq 'Negative' || $s eq 'negative' ? -1 : 0;
  1. # use Switch;
  2. my $s = 'zero';
  3. my $x;
  4. switch ($s) {
  5. case 'Positive' { $x = 1; }
  6. case 'positive' { $x = 1; }
  7. case 'Negative' { $x = -1; }
  8. case 'negative' { $x = -1; }
  9. else { $x = 0; }
  10. }

型に応じた文字列を変数に代入する

Java

Java 21以降
  1. Object obj = ...;
  2. String s = switch (obj) {
  3. case String s2 -> s2 + s2; // 文字列の場合は2つ並べる
  4. case Integer i -> Integer.toString(i.intValue() * 2); // 整数の場合は2倍する
  5. default -> obj.getClass().getName(); // それ以外の場合は型名
  6. };
Java 16以降
  1. Object obj = ...;
  2. String s;
  3. if (obj instanceof String s2) { // 文字列の場合は2つ並べる
  4. s = s2 + s2;
  5. } else if (obj instanceof Integer i) { // 整数の場合は2倍する
  6. s = Integer.toString(i.intValue() * 2);
  7. } else { // それ以外の場合は型名
  8. s = obj.getClass().getName();
  9. }
Java 15まで
  1. Object obj = ...;
  2. String s;
  3. if (obj instanceof String) { // 文字列の場合は2つ並べる
  4. s = (String)obj + obj;
  5. } else if (obj instanceof Integer) { // 整数の場合は2倍する
  6. s = Integer.toString(((Integer)obj).intValue() * 2);
  7. } else { // それ以外の場合は型名
  8. s = obj.getClass().getName();
  9. }

Groovy

  1. def obj = ...
  2. def s
  3. switch (obj) {
  4. case String: // 文字列の場合は2つ並べる
  5. s = obj * 2
  6. break
  7. case Number: // 数値の場合は2倍する
  8. s = (obj * 2).toString()
  9. break
  10. default: // それ以外の場合は型名
  11. s = obj.class.name
  12. }

Kotlin

  1. val obj = ...
  2. val s = when (obj) {
  3. is String -> obj + obj
  4. is Int -> obj * 2
  5. else -> obj.getClass().getName()
  6. }

Scala

  1. val any: Any = ...
  2. val s = any match {
  3. case s: String => s * 2 // 文字列の場合は2つ並べる
  4. case i: Int => (i * 2).toString // 整数の場合は2倍する
  5. case a: AnyRef => a.getClass.getName // それ以外の場合は型名
  6. }

Erlang

  1. Obj = ...,
  2. S = if
  3. is_list(Obj) -> Obj ++ Obj; %% 文字列(文字のリスト)の場合は2つ並べる
  4. is_integer(Obj) -> Obj * 2; %% 整数の場合は2倍する
  5. true -> io:format("~p", [Obj]) %% それ以外の場合は文字列表現
  6. end.

PowerShell

  1. $obj = ...
  2. $s = switch ($obj) {
  3. { $_ -is [string] } { $_ * 2 } # 文字列の場合は2つ並べる
  4. { $_ -is [int] } { ($_ * 2).ToString() } # 整数の場合は2倍する
  5. default { $_.GetType().FullName } # それ以外の場合は型名
  6. }

F#

  1. let obj = ...
  2. let s = match obj with
  3. | :? string as s -> s + s // 文字列の場合は2つ並べる
  4. | :? int as i -> (i * 2).ToString() // 整数の場合は2倍する
  5. | _ -> obj.GetType().FullName // それ以外の場合は型名

C#

C# 8.0以降
  1. object obj = ...;
  2. string s = obj switch {
  3. string s2 => s2 + s2,
  4. int i => (i * 2).ToString(),
  5. _ => obj.GetType().FullName
  6. };
C# 7.0以降
  1. object obj = ...;
  2. string s;
  3. switch (obj) {
  4. case string s2:
  5. s = s2 + s2;
  6. break;
  7. case int i:
  8. s = (i * 2).ToString();
  9. break;
  10. default:
  11. s = obj.GetType().FullName;
  12. break;
  13. }

Go

  1. obj := ...
  2. var s string
  3. switch t := obj.(type) {
  4. case string: // 文字列の場合は2つ並べる
  5. s = t + t
  6. case int: // 整数の場合は2倍する
  7. s = fmt.Sprintf("%d", t * 2)
  8. default: // それ以外の場合は型名
  9. s = fmt.Sprintf("%T", t)
  10. }

Rust

  1. let obj: &dyn Any = ...
  2. let s = if let Some(s) = obj.downcast_ref::<&str>() {
  3. format!("{0}{0}", s)
  4. } else if let Some(n) = obj.downcast_ref::<i32>() {
  5. format!("{}", n * 2)
  6. } else {
  7. obj.type_id().as_ref().name().unwrap_or_else(|| "").to_string()
  8. };

Dart

Dart 3.0以降
  1. var obj = ...;
  2. var s = switch (obj) {
  3. (String str) => str + str, // 文字列の場合は2つ並べる
  4. (int n) => '${n * 2}', // 数値の場合は2倍する
  5. _ => '$obj', // それ以外の場合は文字列表現
  6. };

TypeScript

  1. let obj = ...;
  2. let t = typeof obj;
  3. let s: string;
  4. switch (t) {
  5. case 'string': // 文字列の場合は2つ並べる
  6. s = obj + obj;
  7. break;
  8. case 'number': // 数値の場合は2倍する
  9. s = String(obj * 2);
  10. break;
  11. default: // それ以外の場合は型名
  12. s = t;
  13. }

JavaScript

  1. let obj = ...;
  2. let t = typeof obj;
  3. let s;
  4. switch (t) {
  5. case 'string': // 文字列の場合は2つ並べる
  6. s = obj + obj;
  7. break;
  8. case 'number': // 数値の場合は2倍する
  9. s = String(obj * 2);
  10. break;
  11. default: // それ以外の場合は型名
  12. s = t;
  13. }

CoffeeScript

  1. obj = ...
  2. t = typeof obj
  3. s = switch t
  4. when 'string' then obj + obj # 文字列の場合は2つ並べる
  5. when 'number' then String obj * 2 # 数値の場合は2倍する
  6. else t # それ以外の場合は型名

Ruby

  1. obj = ...
  2. s = case obj
  3. when String then obj * 2 # 文字列の場合は2つ並べる
  4. when Numeric then (obj * 2).to_s # 数値の場合は2倍する
  5. else obj.class.name # それ以外の場合は型名
  6. end
Ruby 2.7以降
  1. obj = ...
  2. s = case obj
  3. in String then obj * 2 # 文字列の場合は2つ並べる
  4. in Numeric then (obj * 2).to_s # 数値の場合は2倍する
  5. in _ then obj.class.name # それ以外の場合は型名
  6. end

Python

  1. obj = ...
  2. s = (obj * 2 if isinstance(obj, str) else # 文字列の場合は2つ並べる
  3. str(obj * 2) if isinstance(obj, int) else # 整数の場合は2倍する
  4. type(obj).__name__) # それ以外の場合は型名

PHP

  1. $obj = ...
  2. $type = gettype($obj);
  3. switch ($type) {
  4. case 'string': // 文字列の場合は2つ並べる
  5. $s = $obj . $obj;
  6. break;
  7. case 'integer': // 数値の場合は2倍する
  8. $s = (string)($obj * 2);
  9. break;
  10. case 'object': // オブジェクトの場合はクラス名
  11. $s = get_class($obj);
  12. break;
  13. default: // それ以外(配列など)は型名
  14. $s = $type;
  15. }
PHP 8.0以降
  1. $obj = ...
  2. $type = gettype($obj);
  3. $s = match ($type) {
  4. 'string' => $obj . $obj, // 文字列の場合は2つ並べる
  5. 'integer' => (string)($obj * 2), // 数値の場合は2倍する
  6. 'object' => get_class($obj), // オブジェクトの場合はクラス名
  7. default => $type, // それ以外(配列など)は型名
  8. };

指定された年が閏年かどうかを判定する関数

Java

  1. public static boolean isLeapYear(int year) {
  2. if (year % 400 == 0) return true; // 400で割り切れる年は、閏年である
  3. if (year % 100 == 0) return false; // 400で割り切れず100で割り切れる年は、閏年でない
  4. if (year % 4 == 0) return true; // 100で割り切れず4で割り切れる年は、閏年である
  5. return false; // 4で割り切れない年は、閏年でない
  6. }

Groovy

  1. def isLeapYear(year) {
  2. if (year % 400 == 0) true; // 400で割り切れる年は、閏年である
  3. else if (year % 100 == 0) false; // 400で割り切れず100で割り切れる年は、閏年でない
  4. else if (year % 4 == 0) true; // 100で割り切れず4で割り切れる年は、閏年である
  5. else false // 4で割り切れない年は、閏年でない
  6. }

Kotlin

  1. fun isLeapYear(year: Int) =
  2. if (year % 400 == 0) true // 400で割り切れる年は、閏年である
  3. else if (year % 100 == 0) false // 400で割り切れず100で割り切れる年は、閏年でない
  4. else if (year % 4 == 0) true // 100で割り切れず4で割り切れる年は、閏年である
  5. else false // 4で割り切れない年は、閏年でない

Scala

  1. def isLeapYear(year: Int) =
  2. (year % 4, year % 100, year % 400) match {
  3. case (0, 0, 0) => true // 400で割り切れる年は、閏年である
  4. case (0, 0, _) => false // 400で割り切れず100で割り切れる年は、閏年でない
  5. case (0, _, _) => true // 100で割り切れず4で割り切れる年は、閏年である
  6. case (_, _, _) => false // 4で割り切れない年は、閏年でない
  7. }

Erlang

  1. is_leap_year(Year) -> is_leap_year(Year rem 4, Year rem 100, Year rem 400).
  2. is_leap_year(0, 0, 0) -> true; %% 400で割り切れる年は、閏年である
  3. is_leap_year(0, 0, _) -> false; %% 400で割り切れず100で割り切れる年は、閏年でない
  4. is_leap_year(0, _, _) -> true; %% 100で割り切れず4で割り切れる年は、閏年である
  5. is_leap_year(_, _, _) -> false. %% 4で割り切れない年は、閏年でない

Haskell

  1. isLeapYear year =
  2. case (year `mod` 4, year `mod` 100, year `mod` 400) of
  3. (0, 0, 0) -> True -- 400で割り切れる年は、閏年である
  4. (0, 0, _) -> False -- 400で割り切れず100で割り切れる年は、閏年でない
  5. (0, _, _) -> True -- 100で割り切れず4で割り切れる年は、閏年である
  6. (_, _, _) -> False -- 4で割り切れない年は、閏年でない

PowerShell

  1. function isLeapYear($year) {
  2. switch ($year) {
  3. { $_ % 400 -eq 0 } { return $True } # 400で割り切れる年は、閏年である
  4. { $_ % 100 -eq 0 } { return $False } # 400で割り切れず100で割り切れる年は、閏年でない
  5. { $_ % 4 -eq 0 } { return $True } # 100で割り切れず4で割り切れる年は、閏年である
  6. default { return $False } # 4で割り切れない年は、閏年でない
  7. }
  8. }

F#

  1. let isLeapYear year =
  2. match year % 4, year % 100, year % 400 with
  3. | 0, 0, 0 -> true // 400で割り切れる年は、閏年である
  4. | 0, 0, _ -> false // 400で割り切れず100で割り切れる年は、閏年でない
  5. | 0, _, _ -> true // 100で割り切れず4で割り切れる年は、閏年である
  6. | _, _, _ -> false // 4で割り切れない年は、閏年でない
  1. let (|DivisibleBy|_|) divider dividee =
  2. if dividee % divider = 0 then Some() else None
  3. let isLeapYear year =
  4. match year with
  5. | DivisibleBy 400 -> true // 400で割り切れる年は、閏年である
  6. | DivisibleBy 100 -> false // 400で割り切れず100で割り切れる年は、閏年でない
  7. | DivisibleBy 4 -> true // 100で割り切れず4で割り切れる年は、閏年である
  8. | _ -> false // 4で割り切れない年は、閏年でない

C#

  1. public static bool IsLeapYear(int year) {
  2. if (year % 400 == 0) return true; // 400で割り切れる年は、閏年である
  3. if (year % 100 == 0) return false; // 400で割り切れず100で割り切れる年は、閏年でない
  4. if (year % 4 == 0) return true; // 100で割り切れず4で割り切れる年は、閏年である
  5. return false; // 4で割り切れない年は、閏年でない
  6. }
C# 8.0以降
  1. public static bool IsLeapYear(int year) => (year % 4, year % 100, year % 400) switch {
  2. (0, 0, 0) => true, // 400で割り切れる年は、閏年である
  3. (0, 0, _) => false, // 400で割り切れず100で割り切れる年は、閏年でない
  4. (0, _, _) => true, // 100で割り切れず4で割り切れる年は、閏年である
  5. _ => false // 4で割り切れない年は、閏年でない
  6. };

C++

  1. bool is_leap_year(const int year) {
  2. if (year % 400 == 0) return true; // 400で割り切れる年は、閏年である
  3. if (year % 100 == 0) return false; // 400で割り切れず100で割り切れる年は、閏年でない
  4. if (year % 4 == 0) return true; // 100で割り切れず4で割り切れる年は、閏年である
  5. return false; // 4で割り切れない年は、閏年でない
  6. }

Go

  1. func IsLeapYear(year int) bool {
  2. switch 0 {
  3. case year % 400: return true // 400で割り切れる年は、閏年である
  4. case year % 100: return false // 400で割り切れず100で割り切れる年は、閏年でない
  5. case year % 4: return true // 100で割り切れず4で割り切れる年は、閏年である
  6. }
  7. return false // 4で割り切れない年は、閏年でない
  8. }

Rust

  1. pub fn is_leap_year(year: i32) -> bool {
  2. match (year % 4, year % 100, year % 400) {
  3. (0, 0, 0) => true,
  4. (0, 0, _) => false,
  5. (0, _, _) => true,
  6. (_, _, _) => false,
  7. }
  8. }

Dart

  1. bool isLeapYear(int year) {
  2. switch (0) {
  3. case year % 400: return true; // 400で割り切れる年は、閏年である
  4. case year % 100: return false; // 400で割り切れず100で割り切れる年は、閏年でない
  5. case year % 4: return true; // 100で割り切れず4で割り切れる年は、閏年である
  6. }
  7. return false; // 4で割り切れない年は、閏年でない
  8. }

TypeScript

  1. function isLeapYear(year: number) {
  2. switch (0) {
  3. case year % 400: return true; // 400で割り切れる年は、閏年である
  4. case year % 100: return false; // 400で割り切れず100で割り切れる年は、閏年でない
  5. case year % 4: return true; // 100で割り切れず4で割り切れる年は、閏年である
  6. }
  7. return false; // 4で割り切れない年は、閏年でない
  8. }

JavaScript

  1. function isLeapYear(year) {
  2. switch (0) {
  3. case year % 400: return true; // 400で割り切れる年は、閏年である
  4. case year % 100: return false; // 400で割り切れず100で割り切れる年は、閏年でない
  5. case year % 4: return true; // 100で割り切れず4で割り切れる年は、閏年である
  6. }
  7. return false; // 4で割り切れない年は、閏年でない
  8. }

CoffeeScript

  1. isLeapYear = (year) ->
  2. _ = switch 0
  3. when year % 400 then true # 400で割り切れる年は、閏年である
  4. when year % 100 then false # 400で割り切れず100で割り切れる年は、閏年でない
  5. when year % 4 then true # 100で割り切れず4で割り切れる年は、閏年である
  6. else false # 4で割り切れない年は、閏年でない

Ruby

  1. def is_leap_year year
  2. case 0
  3. when year % 400 ; true # 400で割り切れる年は、閏年である
  4. when year % 100 ; false # 400で割り切れず100で割り切れる年は、閏年でない
  5. when year % 4 ; true # 100で割り切れず4で割り切れる年は、閏年である
  6. else ; false # 4で割り切れない年は、閏年でない
  7. end
  8. end
  1. def is_leap_year year
  2. divisible_by = -> (divider) {
  3. -> (dividee) { dividee % divider == 0 }
  4. }
  5. case year
  6. when divisible_by.(400) ; true # 400で割り切れる年は、閏年である
  7. when divisible_by.(100) ; false # 400で割り切れず100で割り切れる年は、閏年でない
  8. when divisible_by.( 4) ; true # 100で割り切れず4で割り切れる年は、閏年である
  9. else ; false # 4で割り切れない年は、閏年でない
  10. end
  11. end
Ruby 2.7以降
  1. def is_leap_year year
  2. case [year % 4, year % 100, year % 400]
  3. in [0, 0, 0] ; true # 400で割り切れる年は、閏年である
  4. in [0, 0, _] ; false # 400で割り切れず100で割り切れる年は、閏年でない
  5. in [0, _, _] ; true # 100で割り切れず4で割り切れる年は、閏年である
  6. in [_, _, _] ; false # 4で割り切れない年は、閏年でない
  7. end
  8. end

Python

  1. def is_leap_year(year):
  2. return (True if year % 400 == 0 # 400で割り切れる年は、閏年である
  3. else False if year % 100 == 0 # 400で割り切れず100で割り切れる年は、閏年でない
  4. else True if year % 4 == 0 # 100で割り切れず4で割り切れる年は、閏年である
  5. else False) # 4で割り切れない年は、閏年でない

PHP

  1. function isLeapYear($year) {
  2. if ($year % 400 === 0) return true; // 400で割り切れる年は、閏年である
  3. if ($year % 100 === 0) return false; // 400で割り切れず100で割り切れる年は、閏年でない
  4. if ($year % 4 === 0) return true; // 100で割り切れず4で割り切れる年は、閏年である
  5. return false; // 4で割り切れない年は、閏年でない
  6. }

Perl

  1. sub is_leap_year {
  2. my $year = shift;
  3. $year % 400 or return 1; # 400で割り切れる年は、閏年である
  4. $year % 100 or return 0; # 400で割り切れず100で割り切れる年は、閏年でない
  5. $year % 4 or return 1; # 100で割り切れず4で割り切れる年は、閏年である
  6. return 0; # 4で割り切れない年は、閏年でない
  7. }
  1. sub is_leap_year {
  2. my $year = shift;
  3. return 1 unless $year % 400; # 400で割り切れる年は、閏年である
  4. return 0 unless $year % 100; # 400で割り切れず100で割り切れる年は、閏年でない
  5. return 1 unless $year % 4; # 100で割り切れず4で割り切れる年は、閏年である
  6. return 0; # 4で割り切れない年は、閏年でない
  7. }

戻る

目次

複数行の文字列リテラル Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
文字列中に変数の値を埋め込む(printf など) Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
同じ文字列を繰り返す Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
文字列中の文字の並びを逆にする Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
正規表現を使って、日付を表す文字列から年・月・日を取り出す Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
正規表現を使って、日付を表す文字列を全て抜き出す Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
正規表現を使って、日付を表す文字列の区切りを全てハイフンからスラッシュに置き換える Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
文字列の値に応じた数値を変数に代入する(多分岐) Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
型に応じた文字列を変数に代入する Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
指定された年が閏年かどうかを判定する関数 Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl