正则很强大,每次用每次查。故整理一下,基于Unity3D平台,做一些常用的操作测试。
正则表达式是一种匹配输入文本的模式。.Net 框架提供了允许这种匹配的正则表达式引擎。模式由一个或多个字符、运算符和结构组成。
常用如下:
直接上代码:
usingSystem.Collections;
usingSystem.Collections.Generic;
usingUnityEngine;
usingSystem.Text.RegularExpressions;
publicclassNewBehaviourScript : MonoBehaviour
{
voidStart()
{
TestIsMatch();
TestMatch();
TestSplit();
TestGroup();
TestDelegate();
TestReplace();
}
///
/// IsMatch
///
privatevoidTestIsMatch()
{
boola = Regex.IsMatch("3234", @"\d");
Debug.Log(a); //true
boolb = Regex.IsMatch("fdasg", @"\d");
Debug.Log(b); //false
}
///
/// Match
///
privatevoidTestMatch()
{
stringstr1 = "9s%!@av3g#$|+90发=额~72";
stringpattern1 = @"\d|[a-z]"; //十进制数字匹配或 a-z之前的的单个字符
MatchCollectioncol = Regex.Matches(str1, pattern1);
foreach (Matchmatchincol) //遍历了所有符合规则的
{
Debug.Log(match.ToString());
}
}
///
/// Split
///
privatevoidTestSplit()
{
stringstr2 = "aa;bb,cc.dd[ee.ff";
stringpattern2 = @"[;,.]";
string[] strArray = Regex.Split(str2, pattern2); //多个拆分
for (inti = 0; i < strArray.Length; i++)
{
Debug.Log(strArray[i]);
}
}
///
/// Group 分组
///
privatevoidTestGroup()
{
//分组
stringline = "lane=1;speed=30.3mph;acceleration=2.5mph/s";
Regexreg = newRegex(@"speed\s*=\s*([\d\.]+)\s*(mph|km/h|m/s)*");
Matchmatchs = reg.Match(line);
Debug.Log(matchs.Groups[0].Value); //speed=30.3mph
Debug.Log(matchs.Groups[1].Value); //30.3
Debug.Log(matchs.Groups[2].Value); //mph
//分组命名访问 利用 (?
RegexregCreatKey = newRegex(@"speed\s*=\s*(?
MatchmatchsKey = regCreatKey.Match(line);
Debug.Log(matchsKey.Groups[0].Value); //speed=30.3mph
Debug.Log(matchsKey.Groups[1].Value); //30.3
Debug.Log(matchsKey.Groups[2].Value); //mph
Debug.Log(matchsKey.Groups["name1"].Value);//30.3
Debug.Log(matchsKey.Groups["name2"].Value);//mph
}
///
///使用MatchEvaluator委托
///
privatevoidTestDelegate()
{
varsource = "123abc456ABCD789";
Regexregex = newRegex("[A-Z]{3}", RegexOptions.IgnoreCase); //忽略大小写
varnewSource = regex.Replace(source, newMatchEvaluator(OutPutMatch));
Debug.Log("原字符串:" + source); //原字符串:123abc456ABCD789
Debug.Log("替换后的字符串:" + newSource); //替换后的字符串:123 - abc - 456 - ABC - D789
}
privatestringOutPutMatch(Matchmatch)
{
return"-" + match.Value + "-";
}
///
///匹配替换
///
voidTestReplace()
{
stringstr = "aasb说什么啊";
stringpattern1 = @"a|b|什么阿"; //全字匹配 --res1 :**s*说什么啊
stringpattern2 = @"[ab什么]"; //只要有就匹配 --res2 :**s*说**啊
stringpattern3 = "^";
stringres1 = Regex.Replace(str, pattern1, "*");
Debug.Log("res1:" + res1); //res1 :**s*说什么啊
stringres2 = Regex.Replace(str, pattern2, "*");
Debug.Log("res2:" + res2); //res2 :**s*说**啊
stringres3 = Regex.Replace(str, pattern3, "开始:");
Debug.Log("res3:" + res3); //res3 :开始:aasb说什么啊
stringzb = "(120,30)";
stringr = Regex.Replace(zb, @"\(|\)", "");
string[] array = r.Split(',');
intx = int.Parse(array[0]);
inty = int.Parse(array[1]);
Debug.Log("x:" + x + " ___ y :" + y); //x :120 ___ y :30
MatchCollectioncol = Regex.Matches(zb, @"\d*,\d*");
foreach (varitemincol)
{
Debug.Log("__" +item.ToString()); //__120,30
}
}
}