0

I am looking for a regular expression where i can extract portion of a string that meets the criteria.

string lookup "The length is 32.00 mm".

I would like to be able to get "32.00". Basically the first numeric value before " mm ". in a burte force kind of way, it can be done like this:

string test = "The length is 32.00 mm";

      int idx = test.IndexOf(" mm ") - 1;
      int endIdx = idx;
      while (idx > 0)
      {
        Char c = test.ElementAt(idx);
        if (Char.IsDigit(c) == false && c != '.')
        {
          string data = test.Substring(idx + 1, endIdx - idx + 1);
          break;
        }
        idx--;
      }

Do you have any better logic?

I can split the string by space and pick up the entry before the "mm" slot.

Thanks,

1
  • Depending on how precise it must be - even [\d.]+(?=\s+mm) might satisfy Commented Jan 8, 2015 at 4:35

1 Answer 1

2

Well, you can use regex with positive lookahead

\s[\d.]+(?=\s+mm)

Like this

string test = "The length is 32.00 mm";
Console.WriteLine(Regex.Match(test, @"\s[\d.]+(?=\s+mm)").Value);

DEMO

Sign up to request clarification or add additional context in comments.

7 Comments

It is close but it is matching those that don't have space between the digits and mm. "test cc 12.mm" and "test cc 12mm".
@Sam I've changed the regex.. Take a look now
@vks you're not seeing that I've used Regex.Match instead of Matches and the former only gives you the first match, as opposed to the latter. So your regex is a bit overkill
@Sam also, if you want just a single space after the number and before the mm, then use [\d.]+(?= mm)
@EhsanSajjad I would suggest going through www.regular-expressions.info
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.