如何在C#中找到具有角色格式的字符串?

时间:2016-06-10 04:33:00

标签: c#

我想找到字符串格式如下:

numbers.H numbers.numbers'

示例:

1H 34'
4H 89'

我试过这段代码:

string format;
int[] numbers = new int[10] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
foreach(var values in numbers)
{
       format = values + "H " + values + values + "'";
}

注意:此代码似乎失败了。我编码给你很难理解我的问题。 因此,如果我的sourceString的值类似于:4H 89'

我想检查这些值是否具有numbers.H numbers.numbers'

之类的格式

此时,我分析如下: 4是numbers。 H 。 8是numbers。 9是numbers。 =====>格式正确。

我的代码无法找到此字符串。任何人都可以有任何方法来解决我的问题吗?

感谢。

3 个答案:

答案 0 :(得分:5)

试试这个:

string input = "9H 99";
if (Regex.Match(input.ToUpper(), @"\d[A-Z]\s\d\d").Success)
{
   //Match
}
else
{
  //Not
}

答案 1 :(得分:1)

可以使用LinqRegex进行简化,这可能会有所帮助

string[] stringFormat = new string[7] { "1H 34'", "4H 89'", "4H 89", "42 89", "4H 8H'", "345 t3", "4H 333'" };
            List<string> requiredFormattedStrings = new List<string>();
            foreach (var stringValue in stringFormat)
            {
                string[] val = stringValue.Split(' ');
                if ((val[0].Length == 2 && val[0].EndsWith("H")) && (val[1].Length == 3 && val[1].EndsWith("'")))
                {
                    bool isNumber = Char.IsDigit(val[0], 0);
                    if (isNumber)
                    {
                        string secondString = val[1].Substring(0, 2);
                        bool isNumber2 = secondString.All(c => Char.IsDigit(c));
                        if(isNumber2)
                        {
                            requiredFormattedStrings.Add(stringValue);
                        }
                    }
                }
            }

<强>输出

1H 34'4H 89'

答案 2 :(得分:1)

@Dr。缝合答案是最好的。如果你想了解正则表达式模式。

string input = "9H 99";
if (Regex.Match(input.ToUpper(), @"\d\\H [0-9]{2}").Success)
//This is the pattern if you get only H or else replace '\\H' with'[A-Z]'.
//If you also get small case then add [a-zA-Z]
{
   //Match
}
else
{
  //Not
}