2013-03-21 40 views
0

我需要先取号从字符串,例如如何采取先数量从LINQ C#中的字符串

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

为我用C#代码:

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

如何通过LINQ做同样的事情?

谢谢!

+2

http://stackoverflow.com/a/15550651/1283124但使用'取(1)' – 2013-03-21 15:21:08

+0

对不起,但我需要别的东西 – ihorko 2013-03-21 15:23:04

+1

' “有些值123
这也是麻木2”'应该产生'123'还是错误? – 2013-03-21 15:23:41

回答

8

你可以尝试Enumerable.TakeWhile

ebayOrderId.TakeWhile(c => char.IsDigit(c)); 
+1

+1,优于正则表达式 – 2013-03-21 15:22:43

+0

是的,这正是我所需要的。谢谢! – ihorko 2013-03-21 15:24:21

+3

请注意,您可以将此缩短为'ebayOrderId.TakeWhile(char.IsDigit)'。 – Lee 2013-03-21 15:35:10

2

您可以使用LINQ TakeWhile得到数字的列表,然后new string得到弦编号

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

我会提高@大卫的回答。 (\d+)[^\d]*:一个数字后跟任何不是数字的数字。

您的号码将是第一组:

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]); 
    } 
} 
相关问题