Get numbers after a specific line

I have a bite containing this text ...

BEGIN Fin Bal -461.000 Day 4 END

BEGIN Fin Bal 88861.000 Day 2 END

BEGIN Fin Bal 456461.000 Day 1 END

BEGIN Fin Bal -44561.000 Day 0 END

I need to extract the value

-461,000

Inclusion if it is negative or not.

I used this ...

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

The problem is that this removes the negative character and also saves the value 4 from the day value.

Is there a way to get the numerical value after the word Bel effectively? Excluding text after desired value?

Thanks, Paul.

+4
source share
5 answers

For a LINQ solution that captures the first number:

 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()); 
+3
source

Try it, it can help you.

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

See Lookahead and Lookbehind Zero Width Statements

Explanation

 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

+1
source

You can use this regex:

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

Inside System.Text.RegularExpressions.Regex.Match() .

0
source

For regular expression, try the following and get the first capture:

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

But if your text is always in the format "blah blah Bal NUMBER Day blah blah", how about:

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

RedFilter's answer is nice and compact, but LINQ is not a very efficient method here: it will go through "BEGIN", "Fin" and "Bal" before it gets to your number. Also note that the RedFilter method uses both TryParse and Parse for the same operation (I understand that this is a side effect of LINQ, but this is an extra overhead). If this is the fourth item on your line, you can try something similar to:

  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); } 
0
source

Source: https://habr.com/ru/post/1439199/


All Articles