C#字符串的常用操作工具类代码分享
时间:2022-08-30 16:52:24
实现以下功能:
验证字符串是否由正负号(+-)、数字、小数点构成,并且最多只有一个小数点
验证字符串是否仅由[0-9]构成
验证字符串是否由字母和数字构成
验证是否为空字符串。若无需裁切两端空格,建议直接使用 String.IsNullOrEmpty(string)
裁切字符串(中文按照两个字符计算)
裁切字符串(中文按照两个字符计算,裁切前会先过滤 Html 标签)
过滤HTML标签
获取字符串长度。与string.Length不同的是,该方法将中文作 2 个字符计算。
将形如 10.1MB 格式对用户友好的文件大小字符串还原成真实的文件大小,单位为字节。
根据文件夹命名规则验证字符串是否符合文件夹格式
根据文件名命名规则验证字符串是否符合文件名格式
验证是否为合法的RGB颜色字符串
C#代码:
public static class ExtendedString
{
/// <summary>
/// 验证字符串是否由正负号(+-)、数字、小数点构成,并且最多只有一个小数点
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumeric(this string str)
{
Regex regex = new Regex(@"^[+-]?\d+[.]?\d*$");
return regex.IsMatch(str);
}
/// <summary>
/// 验证字符串是否仅由[0-9]构成
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumericOnly(this string str)
{
Regex regex = new Regex("[0-9]");
return regex.IsMatch(str);
}
/// <summary>
/// 验证字符串是否由字母和数字构成
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumericOrLetters(this string str)
{
Regex regex = new Regex("[a-zA-Z0-9]");
return regex.IsMatch(str);
}
/// <summary>
/// 验证是否为空字符串。若无需裁切两端空格,建议直接使用 String.IsNullOrEmpty(string)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
/// <remarks>
/// 不同于String.IsNullOrEmpty(string),此方法会增加一步Trim操作。如 IsNullOrEmptyStr(" ") 将返回 true。
/// </remarks>
public static bool IsNullOrEmptyStr(this string str)
{
if (string.IsNullOrEmpty(str)) { return true; }
if (str.Trim().Length == 0) { return true; }
return false;
}
/// <summary>
/// 裁切字符串(中文按照两个字符计算)
/// </summary>
/// <param name="str">旧字符串</param>
/// <param name="len">新字符串长度</param>
/// <param name="HtmlEnable">为 false 时过滤 Html 标签后再进行裁切,反之则保留 Html 标签。</param>
/// <remarks>
/// <para>注意:<ol>
/// <li>若字符串被截断则会在末尾追加“...”,反之则直接返回原始字符串。</li>
/// <li>参数 <paramref name="HtmlEnable"/> 为 false 时会先调用<see cref="uoLib.Common.Functions.HtmlFilter"/>过滤掉 Html 标签再进行裁切。</li>
/// <li>中文按照两个字符计算。若指定长度位置恰好只获取半个中文字符,则会将其补全,如下面的例子:<br/>
/// <code><![CDATA[
/// string str = "感谢使用uoLib。";
/// string A = CutStr(str,4); // A = "感谢..."
/// string B = CutStr(str,5); // B = "感谢使..."
/// ]]></code></li>
/// </ol>
/// </para>
/// </remarks>
public static string CutStr(this string str, int len, bool HtmlEnable)
{
if (str == null || str.Length == 0 || len <= 0) { return string.Empty; }
if (HtmlEnable == false) str = HtmlFilter(str);
int l = str.Length;
#region 计算长度
int clen = 0;//当前长度
while (clen < len && clen < l)
{
//每遇到一个中文,则将目标长度减一。
if ((int)str[clen] > 128) { len--; }
clen++;
}
#endregion
if (clen < l)
{
return str.Substring(0, clen) + "...";
}
else
{
return str;
}
}
/// <summary>
/// 裁切字符串(中文按照两个字符计算,裁切前会先过滤 Html 标签)
/// </summary>
/// <param name="str">旧字符串</param>
/// <param name="len">新字符串长度</param>
/// <remarks>
/// <para>注意:<ol>
/// <li>若字符串被截断则会在末尾追加“...”,反之则直接返回原始字符串。</li>
/// <li>中文按照两个字符计算。若指定长度位置恰好只获取半个中文字符,则会将其补全,如下面的例子:<br/>
/// <code><![CDATA[
/// string str = "感谢使用uoLib模块。";
/// string A = CutStr(str,4); // A = "感谢..."
/// string B = CutStr(str,5); // B = "感谢使..."
/// ]]></code></li>
/// </ol>
/// </para>
/// </remarks>
public static string CutStr(this string str, int len)
{
if (IsNullOrEmptyStr(str)) { return string.Empty; }
else
{
return CutStr(str, len, false);
}
}
/// <summary>
/// 过滤HTML标签
/// </summary>
public static string HtmlFilter(this string str)
{
if (IsNullOrEmptyStr(str)) { return string.Empty; }
else
{
Regex re = new Regex(RegexPatterns.HtmlTag, RegexOptions.IgnoreCase);
return re.Replace(str, "");
}
}
/// <summary>
/// 获取字符串长度。与string.Length不同的是,该方法将中文作 2 个字符计算。
/// </summary>
/// <param name="str">目标字符串</param>
/// <returns></returns>
public static int GetLength(this string str)
{
if (str == null || str.Length == 0) { return 0; }
int l = str.Length;
int realLen = l;
#region 计算长度
int clen = 0;//当前长度
while (clen < l)
{
//每遇到一个中文,则将实际长度加一。
if ((int)str[clen] > 128) { realLen++; }
clen++;
}
#endregion
return realLen;
}
/// <summary>
/// 将形如 10.1MB 格式对用户友好的文件大小字符串还原成真实的文件大小,单位为字节。
/// </summary>
/// <param name="formatedSize">形如 10.1MB 格式的文件大小字符串</param>
/// <remarks>
/// 参见:<see cref="uoLib.Common.Functions.FormatFileSize(long)"/>
/// </remarks>
/// <returns></returns>
public static long GetFileSizeFromString(this string formatedSize)
{
if (IsNullOrEmptyStr(formatedSize)) throw new ArgumentNullException("formatedSize");
long size;
if (long.TryParse(formatedSize, out size)) return size;
//去掉数字分隔符
formatedSize = formatedSize.Replace(",", "");
Regex re = new Regex(@"^([\d\.]+)((?:TB|GB|MB|KB|Bytes))$");
if (re.IsMatch(formatedSize))
{
MatchCollection mc = re.Matches(formatedSize);
Match m = mc[0];
double s = double.Parse(m.Groups[1].Value);
switch (m.Groups[2].Value)
{
case "TB":
s *= 1099511627776;
break;
case "GB":
s *= 1073741824;
break;
case "MB":
s *= 1048576;
break;
case "KB":
s *= 1024;
break;
}
size = (long)s;
return size;
}
throw new ArgumentException("formatedSize");
}
/// <summary>
/// 根据文件夹命名规则验证字符串是否符合文件夹格式
/// </summary>
public static bool IsFolderName(this string folderName)
{
if (IsNullOrEmptyStr(folderName)) { return false; }
else
{
// 不能以 “.” 开头
folderName = folderName.Trim().ToLower();
// “nul”、“aux”、“con”、“com1”、“lpt1”不能为文件夹/文件的名称
// 作为文件夹,只需满足名称不为这几个就行。
switch (folderName)
{
case "nul":
case "aux":
case "con":
case "com1":
case "lpt1":
return false;
default:
break;
}
Regex re = new Regex(RegexPatterns.FolderName, RegexOptions.IgnoreCase);
return re.IsMatch(folderName);
}
}
/// <summary>
/// 根据文件名命名规则验证字符串是否符合文件名格式
/// </summary>
public static bool IsFileName(this string fileName)
{
if (IsNullOrEmptyStr(fileName)) { return false; }
else
{
fileName = fileName.Trim().ToLower();
// 不能以 “.” 开头
// 作为文件名,第一个“.” 之前不能是“nul”、“aux”、“con”、“com1”、“lpt1”
if (fileName.StartsWith(".")
|| fileName.StartsWith("nul.")
|| fileName.StartsWith("aux.")
|| fileName.StartsWith("con.")
|| fileName.StartsWith("com1.")
|| fileName.StartsWith("lpt1.")
) return false;
Regex re = new Regex(RegexPatterns.FileName, RegexOptions.IgnoreCase);
return re.IsMatch(fileName);
}
}
/// <summary>
/// 验证是否为合法的RGB颜色字符串
/// </summary>
/// <param name="color">RGB颜色,如:#00ccff | #039 | ffffcc</param>
/// <returns></returns>
public static bool IsRGBColor(this string color)
{
if (IsNullOrEmptyStr(color)) { return false; }
else
{
Regex re = new Regex(RegexPatterns.HtmlColor, RegexOptions.IgnoreCase);
return re.IsMatch(color);
}
}
public static string GetJsSafeStr(this string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
return str.Replace("\\", "\\\\").Replace("\"", "\\\"");
}
}
标签:C#,字符串
0
投稿
猜你喜欢
springboot解决java.lang.ArrayStoreException异常
2023-06-24 19:22:25
详解Spring Boot + Mybatis 实现动态数据源
2023-06-08 13:53:18
SpringBoot打包发布到linux上(centos 7)的步骤
2023-08-11 06:35:55
Android Activity View加载与绘制流程深入刨析源码
2023-10-02 18:03:48
Java面试题冲刺第二十九天--JVM3
2021-05-24 05:34:26
java实现倒序读取文件功能示例分享
2023-07-12 09:23:54
详解SpringBoot JPA常用注解的使用方法
2023-12-09 17:10:31
Java函数式编程(十二):监控文件修改
2022-08-11 10:21:01
eclipse 联想功能设置技巧
2023-03-18 04:11:39
Android操作系统的架构设计分析
2022-07-12 11:02:26
Netty序列化深入理解与使用
2023-05-24 20:13:07
SpringBoot添加自定义拦截器的实现代码
2023-11-26 13:30:54
Android开发高仿课程表的布局实例详解
2022-02-01 18:33:19
Android Jetpack中Room的使用
2021-11-11 08:43:36
SpringBoot+MQTT+apollo实现订阅发布功能的示例
2021-08-30 22:36:46
C#实现航班预订系统
2021-12-26 02:19:37
SpringBoot整合MongoDB的步骤详解
2023-10-11 17:20:32
SpringBoot 3.0 新特性内置声明式HTTP客户端实例详解
2022-11-25 13:47:20
配置SpringBoot方便的切换jar和war的方法示例
2023-11-22 11:57:54
IDEA中的.iml文件和.idea文件夹
2023-11-23 11:47:19