有没有一种方法可以简化基于字符串中包含的值的设置?

Ala*_*an2 1 c#

目前,我的代码是这样的,但是我想知道是否有一种方法可以简化它。我正在寻找的是字符串“ JLPT N1”,“ JLPT N2”,“ JLPT N3”,“ JLPT N4”,“ JLPT N5”之一,然后当我看到其中一个时,我将设置a的值。phraseSources[seq].JishoJlpt

请注意,以上内容只能一次出现。

            if (nodes2[0].InnerText.Contains("JLPT N5"))
            {
                phraseSources[seq].JishoJlpt = "5";
            }
            if (nodes2[0].InnerText.Contains("JLPT N4"))
            {
                phraseSources[seq].JishoJlpt = "4";
            }
            if (nodes2[0].InnerText.Contains("JLPT N3"))
            {
                phraseSources[seq].JishoJlpt = "3";
            }
            if (nodes2[0].InnerText.Contains("JLPT N2"))
            {
                phraseSources[seq].JishoJlpt = "2";
            }
            if (nodes2[0].InnerText.Contains("JLPT N1"))
            {
                phraseSources[seq].JishoJlpt = "1";
            }
Run Code Online (Sandbox Code Playgroud)

如果有人可以建议我可以简化这一点,将不胜感激。

Aag*_*age 6

您应该调查一下Regular Expressions

此方法将从int文本中获取,然后可以使用。

    using System.Linq;
    using System.Text.RegularExpressions;

    public int ContainedNum(string s)
    {
        var match = Regex
           .Match(s, (@"JLPT N(\d{1})"))
           .Groups
           .Cast<Group>()
           .Skip(1) // the first match is the entire string not the group
           .Single()
           .Value;
        var num = int.Parse(match);
        return num;
    }
Run Code Online (Sandbox Code Playgroud)

假设每个参数始终遵循此模式,且不会大于9。如果不是这种情况,您将需要更加保守地使用,Single()并弄清楚如果不是这种情况,您想要返回什么。

您可以这样使用它:

var text = nodes2[0].InnerText;
var num = ContainedNum(text);
phraseSources[seq].JishoJlpt = num.ToString();
Run Code Online (Sandbox Code Playgroud)