C#Unity中的正则表达式 [英] Regular Expressions in C# Unity

查看:414
本文介绍了C#Unity中的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下形式的字符串:"t1 v2".我需要t和v之后的数字,看起来很简单,我正在这样做:

I have strings in the form of: "t1 v2". and I need the numbers after the t and the v, seems pretty straight forward, im doing:

Regex regex = new Regex("t([0-9])");
MatchCollection matches = regex.Matches(options);
if (matches.Count > 0) {
    foreach (Match match in matches) {
        CaptureCollection captures = match.Captures;
        Debug.Log(captures[0].Value);
    }
}

我尝试了其他一些操作,但是它总是返回"t1",我需要它返回"1".

I've tried a few other things but it always returns "t1" I need it to return "1".

我在这里想念什么?

推荐答案

您不会丢失任何内容,只需从结果中选择正确的捕获内容即可:

You are not missing anything, you just need to pick right capture from result:

        var options = "t1 v2";

        var result = Regex.Matches(options, "[a-zA-Z]([0-9]+)").Cast<Match>().Select(x => int.Parse(x.Groups[1].Value)).ToList();
        Console.WriteLine(string.Join(";", result));//1;2

或更直接

        result = Regex.Matches(options, "[a-zA-Z](?<foo>[0-9]+)", RegexOptions.ExplicitCapture).Cast<Match>().Select(x => int.Parse(x.Groups["foo"].Value)).ToList();
        Console.WriteLine(string.Join(";", result));//1;2

在您的Regex查询中(重要的是,您的查询将丢失't32'等字符串):

And in your Regex query (important to mention, your query will miss 't32' and so on strings):

        result = Regex.Matches(options, "t([0-9])").Cast<Match>().Select(x => int.Parse(x.Groups[1].Value)).ToList();
        Console.WriteLine(string.Join(";", result));//1

这篇关于C#Unity中的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆