Reputation: 149
If I have this string:
18.62 PURCHASE REF 1 829400493183
All I want to pull out is the 18.62
. How would I do that without getting the rest of the string? (For instance, without getting the 829400493183
.
If it would be easier to do this without using regex I am open to suggestion as well.
Marked as C# also because this is going into an application I am working on.
Upvotes: 0
Views: 40
Reputation: 51330
Here's a different solution, as you don't really need Split
for this:
var str = "18.62 PURCHASE REF 1 829400493183";
var value = str.Substring(0, str.IndexOf(' '));
By the way, the Regex solution would look something like this:
var str = "18.62 PURCHASE REF 1 829400493183";
var value = Regex.Match(str, @"^-?[0-9]+(?:\.[0-9]+)").Value;
This validates the number but is still overkill as a simple int.TryParse
will do the job.
You just need to add error checks (IndexOf
returning -1, Match
returning null
).
Upvotes: 1
Reputation: 174696
Seems like op wants the first number rather than first word. If yes then use the below regex and get the first number from group index 1.
Regex rgx = new Regex(@"^\D*(\d+(?:\.\d+)?)");
Upvotes: 0
Reputation: 32566
It could be done without RegEx, assuming that 18.62
is separated by a space from the rest:
string s = "18.62 PURCHASE REF 1 829400493183";
string r = s.Split()[0];
Upvotes: 4