facebook twitter hatena line email

Unity/Csharp/正規表現

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

準備

using System.Text.RegularExpressions;

正規表現マッチ

string str = "hoge a456 piyo";
Match match = Regex.Match(str, "a[0-9]+");
if (match.Success) {
    Debug.Log(match.Value); // a456
}

正規表現カッコマッチ

Match match = Regex.Match("hoge10-5", "^hoge([0-9]*)-([0-9]*)");
Debug.Log(match.Value); // hoge10
Debug.Log(match.Groups[1].Value); // 10
Debug.Log(match.Groups[2].Value); // 5

a-z判定

if (StrUtil.IsAlphabet(name)) {
}
public class StrUtil
{
    // アルファベットのみ
    public static bool IsAlphabet(string name)
    {
        return !Regex.IsMatch(name, @"[^a-zA-Z]");
    }
    // 数字のみ
    public static bool IsNum(string name)
    {
        return !Regex.IsMatch(name, @"[^0-9]");
    }
}

参考:http://increment.hatenablog.com/entry/2015/08/21/060626

エスケープ文字

\\を使ってエスケープする

Match match = Regex.Match(endpoint, "/controller1/action2/\\?id=[\\w]*\\&age=[\\d]*");