以下表达式均为基于整个目标字符串的匹配
中国内地电话号码(可不含区号)
^(\d{3,4}-)?\d{7,8}$
中国内地手机号码
^[1]+[3,5,8]+\d{9}$
中国内地邮政编码
^\d{6}$
中国内地身份证号码
^(\d{15}$|^\d{18}$|^\d{17}[\dXx]{1})$
Email地址
^[\\w!#$%&'*+/=?'{|}~^-]+(?:\\.[!#$%&'*+/=?'{|}~^-]+)*@(?:[A-Za-z0-9-]+\\.)+[A-Za-z]{2,6}$
URL
^(((http|https|ftp|file)://)?((www|ftp)\\.)?)([a-z0-9!@#%&+=\\.]+)((/[a-z0-9!@#%&+-=\\.]+)+)?(\\.[A-Za-z]{2,6})$
IP地址
IPv4
^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
IPv6
^(?:[A-F0-9]{1,4}:){6}(?:[A-F0-9]{1,4}:[A-F0-9]{1,4}|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))$
需在开头添加using System.Text.RegularExpressions;
用法举例
/// <summary>
/// 判断是否是IP地址
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public bool IsIPAddress(string str)
{
bool isIPAddress = false;
// IPv4
if (Regex.IsMatch(str, "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"))
isIPAddress = true;
// IPv6
else if (Regex.IsMatch(str, "^(?:[A-F0-9]{1,4}:){6}(?:[A-F0-9]{1,4}:[A-F0-9]{1,4}|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))$"))
isIPAddress = true;
return isIPAddress;
}