Reputation: 13090
I have following regulare expression string
(\d+)(((.|,)\d+)+)?(ms|s| ms| s)
It validates if user entered a correct string for milliseconds and seconds. Example of possible values are
for further operations I need to seperate out the string and the number, for example, if value entered is 123.45ms
I should get 123.45
and ms
.
As of now I'm only getting the number and string is lost!
I can split the numbers and string in two different steps, but I'm interested in doing at once, any suggetions how can I do it?
Upvotes: 1
Views: 1059
Reputation: 9937
I think you are indeed getting the number and unit, the problem is it's getting put into a larger array element than you think. I would suggest amending your regex to:
(\d+)([\.|,]\d+)?\s?(m?s)
Now you will have your number's integer at 1, decimal if it exists at 2 (or if not it will be empty) and unit at 3. It's a little tidier and you won't get the space in your unit anymore.
Alternatively you could use:
(\d+[\.|,]\d+|\d+)\s?(m?s)
if you always want your number at index 1 and unit at 2.
Upvotes: 1
Reputation: 51481
You are very close. You are already specifying match groups. Have a look at Match.Groups property.
Upvotes: 2
Reputation: 93090
You use groups:
string s = "123.45ms";
Match m = Regex.Match(s, @"(\d+([.,]\d+)?) *(ms|s)");
if (m.Success)
{
Console.WriteLine(m.Groups[1]);
Console.WriteLine(m.Groups[3]);
}
Upvotes: 4