0

I have some strings that contain numbers (sometimes) like

1 teaspoon garlic
1/2 cup of butter
1 1/2 ounce yogurt

I'm trying to parse out the numerical part(including the fractions). So

1 teaspoon garlic = "1"
1/2 cup of butter = "1/2"
1 1/2 ounce yogurt = "1 1/2"

I have some regex that I thought was correct that looks like

Regex re = new Regex(@"^\(\d+(\d*|\s\d+\/\d+)\)$");
var match = re.Match(input);

Doesn't seem to be working though. How I can parse out the matching regex from a string?

Matthew The Terrible
  • 1,589
  • 5
  • 31
  • 53
  • I wouldn't say this is a duplicate being as I'm not trying to convert these to a double by doing math on the results here and just really only care about how to parse out the values using regex. Not by splitting strings on spaces and / – Matthew The Terrible Jul 23 '17 at 04:36
  • 1
    Hey, Matthew. I was working on a regex to parse out the fractional parts when Nkosi closed it. Now I've only tested this in Python, but the grouping and everything works for me. `r'((?P[0-9]+)\s(?P[0-9]+)\/(?P[0-9]+))'`. Mind you, I don't know what C# regex is like. – Cory Madden Jul 23 '17 at 04:39
  • 3
    [`\d(?:[\d \/]*\d)?`](https://regex101.com/r/JeIK0G/1) – Slai Jul 23 '17 at 04:54
  • 1
    Oh nice! I need to spend more time on my regex. – Cory Madden Jul 23 '17 at 04:58
  • @slai is correct. This seems to work. I guess all these years of avoiding regex is coming back to haunt me. Thanks guys. – Matthew The Terrible Jul 23 '17 at 04:59

0 Answers0