字符串超过6个字符的部分,用"..."显示
//用户昵称-Usernicknametxt
if (main.nickName != null)
{
Usernicknametxt.text = main.nickName;
//将字符串转换成数组
char[] charArr = Usernicknametxt.text.ToCharArray();
//正则表达式匹配双字节字符(包括汉字在内),返回true
Regex reg = new Regex("[^\x00-\xff]");
//判断字符串每个字符的字节长度,双字节+2,单字节+1
for (int i = 0; i < charArr.Length; i++)
{
Debug.Log("昵称是否是双字节===" + charArr[i]);
if (reg.IsMatch(charArr[i].ToString()))
{
nickNameindex += 2;
}
else
{
nickNameindex++;
}
if (nickNameindex > 6)
{
Usernicknametxt.text = Usernicknametxt.text.Substring(0, i) + "...";
Debug.Log("昵称===" + Usernicknametxt.text);
yield break;
}
}
}
匹配双字节字符(包括汉字在内):[^\x00-\xff]
应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
String.prototype.len=function(){return this.replace([^\x00-\xff]/g,"aa").length;}
unity正则表达式使用方法:
using System.Text.RegularExpressions;
using UnityEngine;
public class Regex_Test : MonoBehaviour
{
void Start()
{
string temp = "123";
Debug.Log(IsNumber(temp));
}
///<summary>
///匹配正整数
///</summary>
///<param name="strInput"></param>
///<returns></returns>
public bool IsNumber(string strInput)
{
Regex reg = new Regex("^[0-9]*[1-9][0-9]*$");
if (reg.IsMatch(strInput))
{
return true;
}
else
{
return false;
}
}
}