LoginSignup
3
4

More than 5 years have passed since last update.

テキストに特定の文字(列)が含まれているか調べる

Last updated at Posted at 2018-06-12

C#です。
String.Containsを使うやり方、LINQを使うやり方、正規表現を使うやり方で調べます。

特定の文字列(string)が含まれているか調べる

String.Containsを使う。
IndexOfを使って戻り値が0以上か調べるより直感的です。

using System;

var text = "How razorback - jumping frogs can level six piqued gymnasts!";
var target = "jumping";
if (text.Contains(target))
   Console.WriteLine($"{target}が含まれています");

特定の文字(char)が含まれているか調べる

StringIEnumrable<char>を実装しています。
ですので、LINQ のEnumerable.Contains<TSource>が使えます。

using System;
using System.Linq;

var text = "Jackdaws love my big sphinx of quartz";
char target = 'b';
if (text.Contains(target)) // <-拡張メソッドのほうの Contains
    Console.WriteLine($"{target}が含まれています");

Enumerable.Any<TSource>を使うともう少し柔軟です。
for文で探すより直感的です。

using System;
using System.Linq;

var text = "Point of view is worth 80 IQ points.";
if (text.Any(c => char.IsDigit(c)))
    Console.WriteLine("数字が含まれています");

複数の文字列(string)、文字(char) のいずれかが含まれているか調べる

複数ならContains|| でつなぐより、正規表現を使うと簡単です。

using System;
using System.Text.RegularExpressions;

var text = "The quick onyx goblin jumps over the lazy dwarf.";
var pattern = "dragon|goblin|elf";
if (Regex.IsMatch(text, pattern))
    Console.WriteLine("いずれかが含まれています。");

参考

実戦で役立つ C#プログラミングのイディオム/定石&パターン
超良書です。
image.png

3
4
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
3
4