在 C# 中,正则表达式(Regular Expressions)是一种强大的文本处理工具,用于执行各种字符串搜索、替换和验证任务。以下是一些常用的正则表达式示例及其用途:
string emailPattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$";
string urlPattern = @"^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$";
string phonePattern = @"^\+?(\d{1,3})?[-. ]?\(?(\d{3})\)?[-. ]?(\d{3})[-. ]?(\d{4})$";
string idCardPattern = @"^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}[Xx0-9]$";
string ipPattern = @"^((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]?)$";
string blankLinePattern = @"^\s*$";
string hexColorPattern = @"^#(?:[0-9a-fA-F]{3}){1,2}$";
string postalCodePattern = @"^[0-9]{6}$";
string alphanumericPattern = @"^[a-zA-Z0-9]+$";
string htmlTagPattern = @"<(.*)>.*<\/\1>"; 以下是一个使用正则表达式检查字符串是否为有效电子邮件地址的示例:
using System; using System.Text.RegularExpressions; class Program { static void Main() { string email = "example@example.com"; bool isValid = Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"); Console.WriteLine(isValid ? "Valid email." : "Invalid email."); } } DateTime 类在 C# 中提供了大量的 API 来处理日期和时间。以下是一些常用的 DateTime API:
Now: 获取当前本地日期和时间。
UtcNow: 获取协调世界时(UTC)的当前日期和时间。
Today: 获取今天的日期,时间部分为零点。
DateTime(): 创建一个 DateTime 对象,默认为当前时间。
DateTime(long ticks): 从自 0001 年 1 月 1 日以来的滴答数创建 DateTime 对象。
DateTime(int year, int month, int day): 创建指定年、月、日的 DateTime 对象,时间部分默认为零点。
DateTime(int year, int month, day, int hour, int minute): 创建指定年、月、日、时、分的 DateTime 对象。
Add(TimeSpan): 返回一个新的 DateTime 对象,它是将指定的 TimeSpan 值添加到当前对象的时间。
AddDays(double): 返回一个新的 DateTime 对象,它是将指定天数添加到当前对象的时间。
AddHours(double): 返回一个新的 DateTime 对象,它是将指定小时数添加到当前对象的时间。
AddMilliseconds(double): 返回一个新的 DateTime 对象,它是将指定毫秒数添加到当前对象的时间。
AddMinutes(double): 返回一个新的 DateTime 对象,它是将指定分钟数添加到当前对象的时间。
AddMonths(int): 返回一个新的 DateTime 对象,它是将指定月份数添加到当前对象的时间。
AddSeconds(double): 返回一个新的 DateTime 对象,它是将指定秒数添加到当前对象的时间。
AddYears(int): 返回一个新的 DateTime 对象,它是将指定年份数添加到当前对象的时间。
CompareTo(Object): 比较两个 DateTime 对象的顺序。
Equals(Object): 判断两个 DateTime 对象是否相等。
IsDaylightSavingTime(): 判断当前 DateTime 对象是否处于夏令时。
Subtract(TimeSpan): 返回一个新的 DateTime 对象,它是当前对象的时间减去指定的 TimeSpan 值。
ToString(): 将 DateTime 对象转换为字符串。
ToString(String): 使用指定的格式字符串将 DateTime 对象转换为字符串。
ToLocalTime(): 将 DateTime 对象从 UTC 时间转换为本地时间。
ToUniversalTime(): 将 DateTime 对象从本地时间转换为 UTC 时间。
DaysInMonth(int year, int month): 确定指定年份和月份的天数。
IsLeapYear(int year): 确定指定年份是否为闰年。
== 和 !=: 比较两个 DateTime 对象是否相等或不相等。
-: 从 DateTime 对象中减去 TimeSpan 对象。
> 和 <: 比较两个 DateTime 对象的大小。
DateTimeFormatInfo 类提供了格式化 DateTime 对象的方法,例如 GetMonthName(int) 和 GetDayName(int)。
使用这些 API,你可以执行日期和时间的算术、格式化、比较和转换等操作。例如:
DateTime now = DateTime.Now; DateTime tomorrow = now.AddDays(1); int daysInMonth = DateTime.DaysInMonth(2024, 7); bool isLeapYear = DateTime.IsLeapYear(2024); string formattedDate = now.ToString("yyyy-MM-dd");
下一篇:高斯伪谱法求解OCP