如果字符串不以c#2.0中的六个整数开头,请不要设置变量?

时间:2010-11-24 02:33:57

标签: c#

我有

string customer_id;

在for循环中,我分配一个来自数据库请求的值

customer = (Customer)records[i];

我想只在entityId(一个字符串)以六个整数开头时才将customer_id分配给customer.entityId。

所以:

string internal_id = "";
string customer_id = "";
Customer customer;
for (int i = 0, j = (response.pageIndex - 1) * _pageSize; i < records.Length; i++, j++)
{
customer = (Customer)records[i];

internal_id = customer.internalId;
customer_id = customer.entityId;
}

如果entityId类似于xxyyzz,则忽略它,如果它是123456 xxyyzz则分配两个变量。我如何才能最好地执行此检查?

提前致谢

3 个答案:

答案 0 :(得分:2)

Regex.IsMatch(input, @"^\d{6}.*")

搜索

  1. 字符串的开头 - ^
  2. 6位数 - \d{6}
  3. 以下任何字符 - .*
  4. ...并在匹配的情况下返回true。

答案 1 :(得分:0)

if (Regex.IMatch(customer.entityId, @"^\d{6}"))

答案 2 :(得分:0)

如果您需要非正则表达式解决方案:

if (int.TryParse(customer.entityId.Substring(0, 6), out customer_id)) {
    internal_id = customer.internalId;
}