LoginSignup
4

More than 5 years have passed since last update.

C# のファイルパスや正規表現の記述には@(逐語的リテラル)を使う

Last updated at Posted at 2018-06-16

@(逐語的リテラル)は読みやすい

@記号を文字列の先頭につけると見たままの出力になります。
他の言語だとヒアドキュメントなどと呼ばれるものです。(※コメント参照)

@を使うとリテラル内の\記号はエスケープ文字として扱われないため、読みやすいです。

  • ファイルパス
using System.IO;

var path = @"C:\temp\sample.txt";
if (File.Exists(path)) { ... }
  • 正規表現
using System;
using System.Text.RegularExpressions;

// 重複した単語を探す
var pattern = @"\b(\w+?)\s\1\b";
var text = "This this is a nice day. What about this? This tastes good. I saw a a dog.";
foreach (Match match in Regex.Matches(text, pattern, RegexOptions.IgnoreCase))
    Console.WriteLine($"{match.Value} (重複 '{match.Groups[1].Value}') 位置 {match.Index}");

@を使わないと...

  • ファイルパス
var path = "C:\\temp\\sample.txt";
  • 正規表現
var pattern = "\\b(\\w+?)\\s\\1\\b";

\だらけで書く時にはミスりそうですし、読みにくいです。

参考

実戦で役立つ C#プログラミングのイディオム/定石&パターン

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