Regex Negative Numbers

Ant

Member
Joined
May 26, 2025
Messages
5
Location
S. E.. Michigan
Programming Experience
Beginner
I have a string "X = 1800.000, Y = 321.359, Z = -900.000," that I'm trying to split and load into a list Object.

This only gets me the whole decimal number, not the negative sign.
C#:
Regex.Split(strGrp2, @"[^\d.]+");

I've tried the following without success, probably a worse result, the Split seemed random or failed to get the numbers.
C#:
@"(?<!\d.+)-?"
@"-?[0-9]*\.?[0-9]"

I'm building my project in C# net 4.7.2 , do I need to use a different expression?
 
Solution
But anyway, this should match (positive with or without leading plus) or negative numbers:
C#:
[+-]?[\d]+(\.[\d]+)?

You can play with it at:

Interesting site, I book marked it for future use.

Thx!

My current working solution is a little crude but works with the data format I'm iterating through.

C#:
Regex.Split(strGrp2, @"[=]|[,]");
Why don't you split on the comma instead of trying to split on the digits?

Or better yet, use match to actually pull the interesting components out for you instead of splitting and then cherry picking values out of an array?
 
But anyway, this should match (positive with or without leading plus) or negative numbers:
C#:
[+-]?[\d]+(\.[\d]+)?

You can play with it at:
 
But anyway, this should match (positive with or without leading plus) or negative numbers:
C#:
[+-]?[\d]+(\.[\d]+)?

You can play with it at:

Interesting site, I book marked it for future use.

Thx!

My current working solution is a little crude but works with the data format I'm iterating through.

C#:
Regex.Split(strGrp2, @"[=]|[,]");
 
Solution
If you are just splitting on those characters, why even use Regex. Just use String.Split() which will be more efficient than building up and running a state machine.
 
If you are just splitting on those characters, why even use Regex. Just use String.Split() which will be more efficient than building up and running a state machine.

Honestly I can't remember why I went down the Regex rabbit hole. :( I'm loading the source data into a richtextbox and some of the parse/search examples were using it.

Had I been programming in C++ I would have out of habit just used basic string methods.

I will definitely take your advice streamline once I get the basic functionality running.
 
Back
Top Bottom