-2

How to find the immediate integer value written before a string in c#? For example

50+ boxes were ordered, however only 2 are delivered.

I need to know the number of boxes (integer value) written just before "delivered". The output should be 2. I have written a code in c# using Regex:

string line = "50+ boxes were ordered, however only 2 are delivered.";
string boxesDelivered = Regex.Match(line, @"\d+").Value;
//The output I get is 50 instead of 2.
Shivam
  • 83
  • 1
  • 1
  • 11

2 Answers2

1

To get the last number that is followed by the word "delivered", you may use the following pattern:

\b\d+\b(?=[^\d]*\bdelivered\b)

Regex demo.

Here's a full example:

string line = "50+ boxes were ordered, however only 2 are delivered.";

var match = Regex.Match(line, @"\b\d+\b(?=[^\d]*\bdelivered\b)");
if (match.Success)
{
    string boxesDelivered = match.Value;
    // TODO: convert the value to a numeric type or use it as is.

}

Try it online.

0

written just before delivered

I'm going to take that verbatim as your user requirement - find the last number in the string that appears before "delivered".

You can use (\d+)[^\d]*(?:delivered), which says "match any sequence of numbers that does not occur before another sequence of numbers and does occur before delivered".

string line = "50+ boxes were ordered, however only 2 are delivered.";
string boxesDelivered = Regex.Match(line, @"(\d+)[^\d]*(?:delivered)").Groups[1].Value;
// boxesDelivered = 2
V0ldek
  • 9,623
  • 1
  • 26
  • 57