文字列があり、それぞれに次のように格納された RowKey の値が含まれています。
data-RowKey=029
これは、各ファイルで 1 回だけ発生します。C#関数を使用して数値を取得できる方法はありますか、それとも何らかの選択を自分で作成する必要がありますか? linq を提案したチームメイトがいますが、これが文字列でも機能するかどうかはわかりません。また、これをどのように使用できるかもわかりません。
アップデート:
申し訳ありませんが、これをファイルから文字列に変更しました。
文字列があり、それぞれに次のように格納された RowKey の値が含まれています。
data-RowKey=029
これは、各ファイルで 1 回だけ発生します。C#関数を使用して数値を取得できる方法はありますか、それとも何らかの選択を自分で作成する必要がありますか? linq を提案したチームメイトがいますが、これが文字列でも機能するかどうかはわかりません。また、これをどのように使用できるかもわかりません。
アップデート:
申し訳ありませんが、これをファイルから文字列に変更しました。
ここでは、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;
}
}
}
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;
// ...
}
}
}
以下を想定
以下はコードスニペットです
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));
}
}
ファイルに一度しか存在しないと仮定すると、それ以外の場合は例外をスローすることさえあります:
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);