0

I need take first number from the string, for example

"12345 this is a number " => "12345"
"123 <br /> this is also numb 2" => "123"

etc.

for that I use C# code:

    string number = "";
    foreach(char c in ebayOrderId)
    {
        if (char.IsDigit(c))
        {
            number += c;
        }
        else
        {
            break;
        }
    }
    return number;

How is it possible to do same via LINQ ?

Thanks!

3
  • 2
    stackoverflow.com/a/15550651/1283124 but use Take(1) Commented Mar 21, 2013 at 15:21
  • Sorry, but I need something else Commented Mar 21, 2013 at 15:23
  • 1
    "some value 123 <br /> this is also numb 2" should produce 123 or error? Commented Mar 21, 2013 at 15:23

4 Answers 4

8

You could try Enumerable.TakeWhile:

ebayOrderId.TakeWhile(c => char.IsDigit(c));
Sign up to request clarification or add additional context in comments.

6 Comments

+1, better than regular expression
Note you can shorten this to ebayOrderId.TakeWhile(char.IsDigit).
@IlyaIvanov Why is this better than a regex?
@Joce in the order of importance: readable, shorter, faster.
@IlyaIvanov That order is quite subjective, but I get your point.
|
2

You can use LINQ TakeWhile to get the list of digit, then new string to get the string number

var number = new string(ebayOrderId.TakeWhile(char.IsDigit).ToArray());

Comments

0

Use regex

Regex re=new Regex(@"\d+\w");

Try test if this works at http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx

Good luck!

Comments

0

I would improve on @David's answer. (\d+)[^\d]*: A number followed by anything that isn't a number.

Your number will be in the first group:

static void Main(string[] args)
{
    Regex re = new Regex(@"(\d+)[^\d]*", RegexOptions.Compiled);
    Match m = re.Match("123 <br /> this is also numb 2");

    if (m.Success)
    {
        Debug.WriteLine(m.Groups[1]);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.