0
0

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 1 year has passed since last update.

C#で文字列中の正規表現要素をエスケープする

Posted at

1. はじめに

  • 文字列をエスケープする時にエスケープが必要な文字が思い出せない時に簡単に確認したい
  • Regex.Escape, UnEscape メソッドを使用してプログラムを使って機械的に確認したい

2. 開発環境

  • C#
  • .Net 6
  • Visual Studio 2022
  • Windows 11

3. 文字列をエスケープする

using System;
using System.Text.RegularExpressions;

public static void EscapeSample(){
    // 文字列中の記号をエスケープする
    var str = @"().*%!$$$";

    Console.WriteLine(str);
    Coonsole.WriteLine(Regex.escape(str));
}
実行結果
().*%!$$
$\(\)\.\*\%\!$$\$

4. 文字列をアンエスケープする

using System;
using System.Text.RegularExpressions;

public static void UnescapeSample(){
    // 文字列中のエスケープされている記号をアンエスケープする
    var str = @"\(\)\.\*\%\!$$\$";

    Console.WriteLine(str);
    Console.WriteLine(Regex.Unescape(str));
}
実行結果
\(\)\.\*\%\!$$\$
().*%!$$$

5. 参考文献

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?