extract float number from a string

Hello friends
I tried :

using System.Text.RegularExpressions;
string line;
string resultString;
float a;
Regex regex = new Regex(@"[-+]?[0-9]*\.?[0-9]*");
resultString = regex.Match(line).Groups[1].Value;
a=float.Parse(resultString);

it returns “invalid format”
When I remove the parse instruction and when I display resultString the string is empty. I checked that the input string (named line) is correct : it is “Pcy1_7R12=-0.001111971”

IF substitute

Match resultString = regex.Match(line);

for l2 and l6 it works but my problem is to implement it in a loop

Is your string always in the form {itentifier}={float} ?

If so, you could just do:

string[] parts = line.Split('=');
if(parts.Length == 2)
{
  float value = System.Convert.ToSingle(parts[1]);
}

Not as robust as using a well formed regex, but should suffice for the simple example you gave.

I don’t remember how to properly use this kind of syntax [-+]?[0-9].?[0-9]
But… you have an error there i think it should be like this [-+]?[0-9]+(.[0-9]+)?
Edit:
sorry quickly rechecked the wiki, fixed my own error

thks both for your replies.
the format was good. Just changing

string resultString;
while loop
{
...
resultString = regex.Match(line).Groups[1].Value;
}

with

while loop
{
...
Match resultString = regex.Match(line);
}

makes it work even in a loop. Hope this not tricky in terms of memory leaks, I’m not an expert in C#.

The syntax you are using will take “.0” “1.”, “+” “-” and “.” as floats… be careful

By memory leaks I expect you mean garbage generation (memory for the GC to clean up) - I’d assume that using a regex is going to be more costly in terms of memory use and CPU consumption (it’s got a lot more work to do). This is 100% assumption and should not be taken as fact.

BUT, if you’re not doing this in Update() or similar - for example, if you’re only doing this at scene or game start or due to single events happening infrequently, then caring about either is wasted effort. Just use what’s easiest and consult the profiler to find any real world issues.

1 Like