【Unity3D日常開發】(二十六)Unity3D中使用正則表達式
推薦閱讀
CSDN主頁
GitHub開源地址
Unity3D插件分享
簡書地址
我的個人博客
QQ群:1040082875
一、前言
正則表達式,又稱規則表達式。(英語:Regular Expression,在代碼中常簡寫為regex、regexp或RE),計算機科學的一個概念。正則表達式通常被用來檢索、替換那些符合某個模式(規則)的文本。
許多程序設計語言都支持利用正則表達式進行字符串操作。
例如,在Perl中就內建了一個功能強大的正則表達式引擎。正則表達式這個概念最初是由Unix中的工具軟件(例如sed和grep)普及開的。正則表達式通常縮寫成“regex”,單數有regexp、regex,復數有regexps、regexes、regexen。
二、Unity使用正則表達式
匹配正整數:
using System.Text.RegularExpressions; using UnityEngine; public class Regex_Test : MonoBehaviour { void Start() { string temp = "123"; Debug.Log(IsNumber(temp)); } ///
結果:
匹配大寫字母
using System.Text.RegularExpressions; using UnityEngine; public class Regex_Test : MonoBehaviour { void Start() { string temp = "ABC"; Debug.Log(IsNumber(temp)); } ///
結果:
三、Regex 類
Regex 類用于表示一個正則表達式。
下表列出了 Regex 類中一些常用的方法:
如需了解 Regex 類的完整的屬性列表,請參閱微軟的 C# 文檔。
四、常用正則表達式
^-?\d+$ //匹配整數(包含正負整數) ^(-?\d+)(\.\d+)?$ //匹配浮點數(包含正負浮點數) ^[A-Za-z]+$ //匹配26個英文字母(包含大小寫) ^[A-Z]+$ //匹配由26個英文字母(大寫) ^[a-z]+$ //匹配由26個英文字母(小寫) ^[A-Za-z0-9]+$ //匹配由數字和26個英文字母組成的字符串 ^\w+$ //匹配由數字、26個英文字母或者下劃線組成的字符串 \S{6,} //不能為空 六位以上 [^\x00-\xff] //匹配雙字節字符(包括漢字在內) \d+\.\d+\.\d+\.\d+ //匹配ip地址
五、實例
實例 1 、匹配以 ‘m’ 開頭以 ‘e’ 結尾的單詞
using System.Text.RegularExpressions; using UnityEngine; public class Regex_Test : MonoBehaviour { void Start() { string temp = "make maze and manage to measure it"; MatchStr(temp); } public void MatchStr(string str) { Regex reg = new Regex(@"\bm\S*e\b"); MatchCollection mat = reg.Matches(str); foreach (Match item in mat) { Debug.Log(item); } } }
實例2、 替換掉多余的空格
using System.Text.RegularExpressions; using UnityEngine; public class Regex_Test : MonoBehaviour { void Start() { string temp = "Hello World"; MatchStr(temp); } public void MatchStr(string str) { Regex reg = new Regex("\\s+"); Debug.Log(reg.Replace(str, " ")); } }
unity 正則表達式
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。