6

このテキストを含む文字列があります...

BEGIN Fin Bal -461.000 4 日目 END

BEGIN Fin Bal 88861.000 2 日目 END

BEGIN Fin Bal 456461.000 1 日目 END

BEGIN Fin Bal -44561.000 Day 0 END

値を抽出する必要があります

-461.000

ネガティブかどうかも含めて。

私はこれを使用しています...

static string ExtractNumbers(string expr)
{
    //removes all text from string
    return string.Join(null, System.Text.RegularExpressions
                 .Regex.Split(expr, "[^\\d]"));
}

問題は、これにより負の記号が削除され、日の値から 4 が保持されることです。

Bal という単語の後に効率的に数値を取得する方法はありますか? 必要な値の後のテキストを除外しますか?

ありがとう、ポール。

4

5 に答える 5

3

最初の数値を取得する LINQ ソリューションの場合:

string str = "BEGIN Fin Bal -461.000 Day 4 END";
decimal d;
string n = str.Split(' ').Where(s => decimal.TryParse(s, out d)).FirstOrDefault();
Console.WriteLine(n == null ? "(none)" : decimal.Parse(n).ToString());
于 2012-10-11T15:31:51.810 に答える
2

これを試してください、それはあなたを助けるかもしれません

(?<=Bal\s)-?\d+\.\d+

ゼロ幅アサーションの先読みと後読みを参照してください。

説明

Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=Bal\s)»
   Match the characters “Bal” literally «Bal»
   Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s»
Match the character “-” literally «-?»
   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “.” literally «\.»
Match a single digit 0..9 «\d+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

ここに画像の説明を入力

于 2012-10-11T15:23:48.847 に答える
0

正規表現の場合、次を試して最初のキャプチャを取得します。

/Bal (-?\d*?\.?\d*?)/

ただし、テキストが常に「何とかバル NUMBER 日何とか何とか」という形式である場合は、次のようにします。

str.Split(new string[] {"Bal ", " Day"})[1]
于 2012-10-11T15:28:42.227 に答える
0

RedFilter の答えは素晴らしくコンパクトですが、ここでは LINQ はあまり効率的な方法ではありません。番号に到達する前に、「BEGIN」、「Fin」、および「Bal」を通過します。RedFilter のメソッドは、同じ操作に TryParseParse の両方を使用することにも注意してください (これは LINQ の動作の副作用であることは理解していますが、私の考えでは余分なオーバーヘッドです)。常に文字列の 4 番目の項目になる場合は、次のようなことを試してください。

 string val = "BEGIN Fin Bal -461.000 Day 4 END"; 
 float FinBal;
 bool success = float.TryParse(val.Split(' ')[3], NumberStyles.Float, new NumberFormatInfo(), out FinBal);
 if (success)
 {
     Console.WriteLine( "{0:F3}",FinBal);
 }
于 2012-10-11T15:46:19.770 に答える
0

次の正規表現を使用できます。

^([^\d]*?)(-?[0-9.]+).*$

の内部System.Text.RegularExpressions.Regex.Match()

于 2012-10-11T15:23:27.933 に答える