4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

俺様専用・正規表現メモ

Posted at

仕事やら趣味やらでプログラム書くときに正規表現を頻繁に使ってるんだが、
言語によって微妙に実装違うおかげで頻繁にググってる気がするのでメモ。
とりあえず検索と置換ができればなんとかなるんで、そのあたりだけ書いとこ。

c#
using System.Text.RegularExpressions;

// 入力
string input = "VERSION_ALPHA";
// パターン
string pattern = @"^VERSION_(?<sub>.*)$";
// 置換後
string replacement = "VERSION_BETA";
// 検索処理
Match mc= Regex.Match(input, pattern);
// 引っかかったか?
if (mc.Success)
{
    // 名前付きサブパターン抽出
    string sub = match.Groups["sub"].ToString();
    // 置換
    replaced = Regex.Replace(input, pattern, replacement);
}
python
import re

# 入力
input = "VERSION_ALPHA"
# パターン
pattern = "VERSION_(?P<sub>.*)$";
# 置換後
replacement = "VERSION_BETA"

# 検索
mc = re.search(pattern, input)
# 引っかかったか?
if mc:
	# 名前付きサブパターン抽出
	sub = mc.groups("sub")[0]
	# 置換
	replaced = re.sub(pattern, replacement, input)
php
// 入力
$input = "VERSION_ALPHA";
// パターン
$pattern = "/^VERSION_(?<sub>.*)$/";
// 置換後
$replacement = "VERSION_BETA";

// 検索
$mc = preg_match($pattern, $input, $matches);
// 引っかかったか?
if($mc)
{
    // 名前付きサブパターン抽出
    $sub = $matches["sub"];
    // 置換
    $replaced = preg_replace($pattern, $replacement, $input);
}
javascript
// 入力
var input = "VERSION_ALPHA";
// パターン(名前付きサブパは無理っぽい?)
var pattern = /^VERSION_(.*)$/;
// 置換後
var replacement = "VERSION_BETA";

// 検索
var mc = input.match(pattern);
// 引っかかったか?
if(mc)
{
    // サブパターン抽出
    var sub = result[1];
    // 置換
    var replaced = input.replace(pattern, replacement);
}
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?