2

英数字の文字列リストがあります。例えば:

1A
2B
7K
10A

数値部分のみを取得して比較したいのですが、10未満の場合は別のリストに追加する必要はありません。知りたいこと 文字列から数値部分を分割する正規表現。どんな助けでも。私が今までやったことは次のとおりです。

 if (x == y) // also handles null
            return 0;
        if (x == null)
            return -1;
        if (y == null)
            return +1;

        int ix = 0;
        int iy = 0;
        while (ix < x.Length && iy < y.Length)
        {
            if (Char.IsDigit(x[ix]) && Char.IsDigit(y[iy]))
            {
                // We found numbers, so grab both numbers
                int ix1 = ix++;
                int iy1 = iy++;
                while (ix < x.Length && Char.IsDigit(x[ix]))
                    ix++;
                while (iy < y.Length && Char.IsDigit(y[iy]))
                    iy++;
                string numberFromX = x.Substring(ix1, ix - ix1);
                string numberFromY = y.Substring(iy1, iy - iy1);

                // Pad them with 0's to have the same length
                int maxLength = Math.Max(
                    numberFromX.Length,
                    numberFromY.Length);
                numberFromX = numberFromX.PadLeft(maxLength, '0');
                numberFromY = numberFromY.PadLeft(maxLength, '0');

                int comparison = _CultureInfo
                    .CompareInfo.Compare(numberFromX, numberFromY);
                if (comparison != 0)
                    return comparison;
            }
            else
            {
                int comparison = _CultureInfo
                    .CompareInfo.Compare(x, ix, 1, y, iy, 1);
                if (comparison != 0)
                    return comparison;
                ix++;
                iy++;
            }
        }

しかし、私は自分のアプローチをそれほど複雑にしたくありません。したがって、分割するには正規表現が必要です。

4

4 に答える 4

3

char の IsDigit メソッドを試す

var number = int.Parse(new string(someString.Where(char.IsDigit).ToArray()));
if(number<10)
{
   someList.Add(number);
}

使用するAllIsDigit、文字列の数値部分のみを取得し、それを int に解析して比較できます:) 正規表現を使用する必要はありません

于 2013-10-10T06:14:30.327 に答える
2

以下のコードを使用して、入力文字列を分割し、数値グループとアルファ グループの結果を取得できます。1 つのグループが存在しない場合、結果は空の文字列になります。

string input = "10AAA";
Match m = Regex.Match(input, @"(\d*)(\D*)");

string number = m.Groups[1].Value;
string alpha = m.Groups[2].Value;
于 2013-10-10T06:19:27.257 に答える
1

あなたはこれでそれを試すことができます:

  string txt="10A";
  string re1="(\\d+)";  // Integer Number 1

  Regex r = new Regex(re1);
  Match m = r.Match(txt);
于 2013-10-10T06:15:26.673 に答える