0

文字列があり、それぞれに次のように格納された RowKey の値が含まれています。

data-RowKey=029

これは、各ファイルで 1 回だけ発生します。C#関数を使用して数値を取得できる方法はありますか、それとも何らかの選択を自分で作成する必要がありますか? linq を提案したチームメイトがいますが、これが文字列でも機能するかどうかはわかりません。また、これをどのように使用できるかもわかりません。

アップデート:

申し訳ありませんが、これをファイルから文字列に変更しました。

4

4 に答える 4

2

ここでは、Linq はあまり役に立ちません。正規表現を使用して数値を抽出します。

data-Rowkey=(\d+)

アップデート:

Regex r = new Regex(@"data-Rowkey=(\d+)");

string abc =  //;
Match match = r.Match(abc);
if (match.Success) 
{
  string rowKey = match.Groups[1].Value;
}

コード:

public string ExtractRowKey(string filePath)
{
  Regex r = new Regex(@"data-Rowkey=(\d+)");

  using (StreamReader reader = new StreamReader(filePath))
  {
    string line; 
    while ((line = reader.ReadLine()) != null)
    {
      Match match = r.Match(line);
      if (match.Success) return match.Groups[1].Value;
    }
  }
}
于 2012-05-30T14:19:40.063 に答える
1
Regex g = new Regex(@"data-RowKey=(?<Value>\d+)");

using (StreamReader r = new StreamReader("myFile.txt"))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {
        Match m = g.Match(line);
        if (m.Success)
        {
            string v = m.Groups["Value"].Value;
            // ...
        }
    }
}
于 2012-05-30T14:21:24.253 に答える
1

以下を想定

  1. ファイルには data-Row が含まれている必要があります (大文字と小文字を含めて完全に一致)
  2. 数値の長さは 3

以下はコードスニペットです

        var fileNames = Directory.GetFiles("rootDirPath");

        var tuples = new List<Tuple<String, int>>();
        foreach(String fileName in fileNames)
        {
            String fileData =File.ReadAllText(fileName) ;
            int index = fileData.IndexOf("data-RowKey=");
            if(index >=0)
            {
                String numberStr = fileData.Substring(index+12,3);// ASSUMING data-RowKey is always found, and number length is always 3
                int number = 0;
                int.TryParse(numberStr, out number);
                tuples.Add(Tuple.Create(fileName, number));
            }
        }
于 2012-05-30T14:28:55.497 に答える
1

ファイルに一度しか存在しないと仮定すると、それ以外の場合は例外をスローすることさえあります:

String rowKey = null;
try
{
    rowKey = File.ReadLines(path)
                .Where(l => l.IndexOf("data-RowKey=") > -1)
                .Select(l => l.Substring(12 + l.IndexOf("data-RowKey=")))
                .Single();
}
catch (InvalidOperationException) {
    // you might want to log this exception instead
    throw;
}

編集:文字列を使用した単純なアプローチでは、常に長さ 3 の最初の出現を取得します。

rowKey = text.Substring(12 + text.IndexOf("data-RowKey="), 3);
于 2012-05-30T14:33:25.587 に答える