在某个字符串后获取数字

时间:2012-10-11 15:21:01

标签: c# regex

我有一个含有这个文字的刺痛......

  

BEGIN Fin Bal -461.000第4天结束

     

BEGIN Fin Bal 88861.000第2天结束

     

BEGIN Fin Bal 456461.000第1天结束

     

BEGIN Fin Bal -44561.000第0天结束

我需要提取值

  

-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之后有效地获取数值?排除所需值之后的任何文本?

谢谢,保罗。

5 个答案:

答案 0 :(得分: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());

答案 1 :(得分:1)

试试这个,它可能对你有帮助

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

参见 Lookahead and Lookbehind Zero-Width Assertions

解释

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) «+»

enter image description here

答案 2 :(得分:0)

您可以使用此正则表达式:

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

System.Text.RegularExpressions.Regex.Match()内。

答案 3 :(得分:0)

对于正则表达式,请尝试以下操作,并获得第一次捕获:

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

但如果你的文字总是采用“blah blah Bal NUMBER Day blah blah”格式,那该怎么样:

str.Split(new string[] {"Bal ", " Day"})[1]

答案 4 :(得分:0)

RedFilter的答案很好而且紧凑,但LINQ在这里不是一个非常有效的方法:在它到达你的号码之前它会通过“BEGIN”,“Fin”和“Bal”。另请注意,RedFilter的方法同时使用TryParse Parse进行相同的操作(我知道这是LINQ如何工作的副作用,但这是我心中的额外开销)。如果它总是成为字符串中的第四项,您可以尝试类似于:

 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);
 }
相关问题