简体   繁体   中英

How would I write the Regex for this?

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.

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];

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 ).

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+)?)");

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM