很多项目中都会碰到,判断手机号是否合法,邮箱是否合法,网页地址是否合法,文本文件加载以及导出等等,由于使用到的地方实在太多了,每次重新编写方法麻烦,因此我整理了一个工具类脚本,里面提供了多种常用的字符串操作的方法。
工具类中具体方法如下:
1、读取文件内容(返回字符串)
2、导出文本文件
3、异步加载远端文本文件(需要扩写异步Task.GetAwaiter(),列表最后提供了第三方的重写的GetAwaiter,经过测试能满足大部分async方法的使用)
4、判断两个字符串是否相等(字符顺序可以不一致,以及英文字母不区分大小写)
5、判断输入的字符串只包含汉字
6、判断字符串中是否含有中文字符
7、匹配3位或4位区号的电话号码,其中区号可以用小括号括起来,也可以不用,区号与本地号间可以用连字号或空格间隔,也可以没有间隔
8、判断输入的字符串是否是一个合法的手机号
9、判断输入的字符串只包含数字可以匹配整数和浮点数
10、匹配非负整数
11、匹配正整数
12、判断输入的字符串字只包含英文字母
13、判断输入的字符串是否是一个合法的Email地址
14、判断输入的字符串是否只包含数字和英文字母
15、判断输入的字符串是否是一个超链接
16、判断是否有特殊字符
17、判断输入的字符串是否是表示一个IP地址
18、计算字符串的字符长度,一个汉字字符将被计算为两个字符
19、获取字符串Unicode编码的数量,两个个英文字母占一个字节,一个汉字占一个字节
20、调用Regex中IsMatch函数实现一般的正则表达式匹配
21、从输入字符串中的第一个字符开始,用替换字符串替换指定的正则表达式模式的所有匹配项。
22、在由正则表达式模式定义的位置拆分输入字符串。
23、判断输入的字符串是否是合法的IPV6 地址
异步扩写Task.GetAwaiter()的工具,百度网盘链接:https://pan.baidu.com/s/1whJhL9bQKwp3RmbzZxcWOw?pwd=wc4w
提取码:wc4w
以下是工具类完整的代码
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Networking;
public class TextTool
{
public static int bufferSize = 2048 * 2048;
/// <summary>
/// 读取文件内容(返回字符串)
/// </summary>
/// <param name="path"></param>
/// <param name="content"></param>
/// <returns>返回bool,true读取成功,false读取失败</returns>
public static bool ReadContent(string path, ref string content)
{
FileInfo file = new FileInfo(path);
if (!file.Exists)
{
Console.Write("未找到文件");
return false;
}
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize))
{
using (StreamReader sr = new StreamReader(fs, Encoding.Default))
{
content = sr.ReadToEnd();
}
}
return true;
}
/// <summary>
/// 导出文件
/// </summary>
/// <param name="content">导出内容</param>
/// <param name="path">导出路径</param>
/// <returns>返回bool,true导出成功,false导出失败</returns>
public static bool WriteContent(string content, string path, FileMode fileMode = FileMode.Truncate)
{
fileMode = File.Exists(path) ? fileMode : FileMode.CreateNew;
var fileAccess = fileMode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite;
using (FileStream nFile = new FileStream(path, fileMode, FileAccess.ReadWrite, FileShare.ReadWrite, bufferSize))
{
using (StreamWriter sWriter = new StreamWriter(nFile))
{
//写入数据
sWriter.Write(content);
return true;
}
}
}
/// <summary>
/// 异步加载远端文本文件
/// </summary>
/// <param name="url"></param>
/// <param name="CompletedAction"></param>
public static async void LoadAsyncWebContent(string url, Action<bool, string> CompletedAction = null)
{
bool isSuccess = false;
string info = string.Empty;
Debug.Log($"LoadWebText:{url}");
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
await webRequest.SendWebRequest();
if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
{
Debug.Log(webRequest.error);
isSuccess = false;
}
else
{
info = webRequest.downloadHandler.text;
Debug.Log($"LoadWebText:{info}");
isSuccess = true;
}
}
CompletedAction?.Invoke(isSuccess, info);
}
/// <summary>
/// 判断两个字符串是否相等(字符顺序可以不一致,以及英文字母不区分大小写)
/// </summary>
/// <param name="A">字符串A</param>
/// <param name="B">字符串B</param>
/// <returns>返回bool,相等为true,不相等为false</returns>
public static bool StrComparison(string A, string B)
{
char[] c1 = A.ToCharArray();
char[] c2 = B.ToCharArray();
Array.Sort(c1);
Array.Sort(c2);
string t1 = new string(c1).ToLower();
string t2 = new string(c2).ToLower();
if (t1 == t2)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 判断输入的字符串只包含汉字
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsOnlyChinese(string input)
{
if (input == null || input == string.Empty) return false;
Regex regex = new Regex("^[\u4e00-\u9fa5]+$");
return regex.IsMatch(input);
}
/// <summary>
/// 判断字符串中是否含有中文字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public bool IsChinese(string str)
{
if (str == null || str == string.Empty) return false;
char[] ch = str.ToCharArray();
if (str != null)
{
for (int i = 0; i < ch.Length; i++)
{
if (ch[i] >= 0x4E00 && ch[i] <= 0x9FA5)
{
return true;
}
}
}
return false;
}
/// <summary>
/// 匹配3位或4位区号的电话号码,其中区号可以用小括号括起来,
/// 也可以不用,区号与本地号间可以用连字号或空格间隔,
/// 也可以没有间隔
/// \(0\d{2}\)[- ]?\d{8}|0\d{2}[- ]?\d{8}|\(0\d{3}\)[- ]?\d{7}|0\d{3}[- ]?\d{7}
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsPhone(string input)
{
if (input == null || input == string.Empty) return false;
string pattern = "^\\(0\\d{2}\\)[- ]?\\d{8}$|^0\\d{2}[- ]?\\d{8}$|^\\(0\\d{3}\\)[- ]?\\d{7}$|^0\\d{3}[- ]?\\d{7}$";
Regex regex = new Regex(pattern);
return regex.IsMatch(input);
}
/// <summary>
/// 判断输入的字符串是否是一个合法的手机号
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsMobilePhone(string input)
{
if (input == null || input == string.Empty) return false;
string pattern = @"^1[3456789]\d{9}$";
Match match = Regex.Match(input, pattern);
return match.Success;
}
/// <summary>
/// 判断输入的字符串只包含数字
/// 可以匹配整数和浮点数
/// ^-?\d+$|^(-?\d+)(\.\d+)?$
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsNumber(string input)
{
if (input == null || input == string.Empty) return false;
string pattern = "^-?\\d+$|^(-?\\d+)(\\.\\d+)?$";
Regex regex = new Regex(pattern);
return regex.IsMatch(input);
}
/// <summary>
/// 匹配非负整数
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsNotNagtive(string input)
{
if (input == null || input == string.Empty) return false;
Regex regex = new Regex(@"^\d+$");
return regex.IsMatch(input);
}
/// <summary>
/// 匹配正整数
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsUint(string input)
{
if (input == null || input == string.Empty) return false;
Regex regex = new Regex("^[0-9]*[1-9][0-9]*$");
return regex.IsMatch(input);
}
/// <summary>
/// 判断输入的字符串字包含英文字母
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsEnglisCh(string input)
{
if (input == null || input == string.Empty) return false;
Regex regex = new Regex("^[A-Za-z]+$");
return regex.IsMatch(input);
}
/// <summary>
/// 判断输入的字符串是否是一个合法的Email地址
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsEmail(string input)
{
if (input == null || input == string.Empty) return false;
string pattern = @"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$";
Match match = Regex.Match(input, pattern);
return match.Success;
}
/// <summary>
/// 判断输入的字符串是否只包含数字和英文字母
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsNumAndEnCh(string input)
{
if (input == null || input == string.Empty) return false;
string pattern = @"^[A-Za-z0-9]+$";
Regex regex = new Regex(pattern);
return regex.IsMatch(input);
}
/// <summary>
/// 判断输入的字符串是否是一个超链接
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsURL(string input)
{
if (input == null || input == string.Empty) return false;
Uri uriResult;
return Uri.TryCreate(input, UriKind.Absolute, out uriResult)
&& uriResult != null
&& !string.IsNullOrEmpty(uriResult.Scheme);
}
/// <summary>
/// 判断是否有特殊字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsSpecialChar(string str)
{
Regex regExp = new Regex("[^0-9a-zA-Z\u4e00-\u9fa5]");
if (regExp.IsMatch(str))
{
return true;
}
return false;
}
/// <summary>
/// 判断输入的字符串是否是表示一个IP地址
/// </summary>
/// <param name="input">被比较的字符串</param>
/// <returns>是IP地址则为True</returns>
public static bool IsIPv4(string input)
{
if (input == null || input == string.Empty) return false;
string[] IPs = input.Split('.');
Regex regex = new Regex(@"^\d+$");
for (int i = 0; i < IPs.Length; i++)
{
if (!regex.IsMatch(IPs[i]))
{
return false;
}
if (Convert.ToUInt16(IPs[i]) > 255)
{
return false;
}
}
return true;
}
/// <summary>
/// 计算字符串的字符长度,一个汉字字符将被计算为两个字符
/// </summary>
/// <param name="input">需要计算的字符串</param>
/// <returns>返回字符串的长度</returns>
public static int GetCount(string input)
{
return Regex.Replace(input, @"[\u4e00-\u9fa5/g]", "aa").Length;
}
/// <summary>
/// 获取字符串Unicode编码的数量,两个个英文字母占一个字节,一个汉字占一个字节
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public static int GetUnicodeCount(string content)
{
if (content == null) return -1; else if (content == string.Empty) return 0;
System.Globalization.StringInfo stringInfo = new System.Globalization.StringInfo(content);
return stringInfo.LengthInTextElements;
}
/// <summary>
/// 调用Regex中IsMatch函数实现一般的正则表达式匹配
/// </summary>
/// <param name="pattern">要匹配的正则表达式模式。</param>
/// <param name="input">要搜索匹配项的字符串</param>
/// <returns>如果正则表达式找到匹配项,则为 true;否则,为 false。</returns>
public static bool IsMatch(string pattern, string input)
{
if (input == null || input == string.Empty) return false;
Regex regex = new Regex(pattern);
return regex.IsMatch(input);
}
/// <summary>
/// 从输入字符串中的第一个字符开始,用替换字符串替换指定的正则表达式模式的所有匹配项。
/// </summary>
/// <param name="pattern">模式字符串</param>
/// <param name="input">输入字符串</param>
/// <param name="replacement">用于替换的字符串</param>
/// <returns>返回被替换后的结果</returns>
public static string Replace(string pattern, string input, string replacement)
{
Regex regex = new Regex(pattern);
return regex.Replace(input, replacement);
}
/// <summary>
/// 在由正则表达式模式定义的位置拆分输入字符串。
/// </summary>
/// <param name="pattern">模式字符串</param>
/// <param name="input">输入字符串</param>
/// <returns></returns>
public static string[] Split(string pattern, string input)
{
Regex regex = new Regex(pattern);
return regex.Split(input);
}
/// <summary>
/// 判断输入的字符串是否是合法的IPV6 地址
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsIPV6(string input)
{
if (input == null || input == string.Empty) return false;
string pattern = "";
string temp = input;
string[] strs = temp.Split(':');
if (strs.Length > 8)
{
return false;
}
int count = GetStringCount(input, "::");
if (count > 1)
{
return false;
}
else if (count == 0)
{
pattern = @"^([\da-f]{1,4}:){7}[\da-f]{1,4}$";
Regex regex = new Regex(pattern);
return regex.IsMatch(input);
}
else
{
pattern = @"^([\da-f]{1,4}:){0,5}::([\da-f]{1,4}:){0,5}[\da-f]{1,4}$";
Regex regex1 = new Regex(pattern);
return regex1.IsMatch(input);
}
}
/* *******************************************************************
* 1、通过“:”来分割字符串看得到的字符串数组长度是否小于等于8
* 2、判断输入的IPV6字符串中是否有“::”。
* 3、如果没有“::”采用 ^([\da-f]{1,4}:){7}[\da-f]{1,4}$ 来判断
* 4、如果有“::” ,判断"::"是否止出现一次
* 5、如果出现一次以上 返回false
* 6、^([\da-f]{1,4}:){0,5}::([\da-f]{1,4}:){0,5}[\da-f]{1,4}$
* ******************************************************************/
/// <summary>
/// 判断字符串compare 在 input字符串中出现的次数
/// </summary>
/// <param name="input">源字符串</param>
/// <param name="compare">用于比较的字符串</param>
/// <returns>字符串compare 在 input字符串中出现的次数</returns>
private static int GetStringCount(string input, string compare)
{
int index = input.IndexOf(compare);
if (index != -1)
{
return 1 + GetStringCount(input.Substring(index + compare.Length), compare);
}
else
{
return 0;
}
}
}