常用的匹配Regex和執行個體
匹配中文字元的Regex: [u4e00-u9fa5]
匹配雙位元組字元(包括漢字在內):[^x00-xff]
應用:計算字串的長度(一個雙位元組字元長度計2,ASCII字元計1)
String.prototype.len=function(){return this.replace([^x00-xff]/g,"aa").length;}
匹配空行的Regex:n[s| ]*r
匹配HTML標記的Regex:/<(.*)>.*</1>|<(.*) />/
匹配首尾空格的Regex:(^s*)|(s*$)
應用:javascript中沒有像vbscript那樣的trim函數,我們就可以利用這個運算式來實現,如下:
String.prototype.trim = function()
{
return this.replace(/(^s*)|(s*$)/g, "");
}
利用Regex分解和轉換IP地址:
下面是利用Regex匹配IP地址,並將IP地址轉換成對應數值的Javascript程式:
function IP2V(ip)
{
re=/(d+).(d+).(d+).(d+)/g //匹配IP地址的Regex
if(re.test(ip))
{
return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1
}
else
{
throw new Error("Not a valid IP address!")
}
}
不過上面的程式如果不用Regex,而直接用split函數來分解可能更簡單,程式如下:
var ip="10.100.20.168"
ip=ip.split(".")
alert("IP值是:"+(ip[0]*255*255*255+ip[1]*255*255+ip[2]*255+ip[3]*1))
匹配Email地址的Regex:w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*
匹配網址URL的Regex:http://([w-]+.)+[w-]+(/[w- ./?%&=]*)?
利用Regex去除字串中重複的字元的演算法程式:[註:此程式不正確,原因見本貼回複]
var s="abacabefgeeii"
var s1=s.replace(/(.).*1/g,"$1")
var re=new RegExp("["+s1+"]","g")
var s2=s.replace(re,"")
alert(s1+s2) //結果為:abcefgi
我原來在CSDN上發貼尋求一個運算式來實現去除重複字元的方法,最終沒有找到,這是我能想到的最簡單的實現方法。思路是使用後向引用取出包括重複的字元,再以重複的字元建立第二個運算式,取到不重複的字元,兩者串聯。這個方法對於字元順序有要求的字串可能不適用。
得用Regex從URL地址中提取檔案名稱的javascript程式,如下結果為page1
s="http://www.9499.net/page1.htm"
s=s.replace(/(.*/){0,}([^.]+).*/ig,"$2")
alert(s)
利用Regex限制網頁表單裡的文字框輸入內容:
用Regex限制只能輸入中文:onkeyup="value=value.replace(/[^u4E00-u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^u4E00-u9FA5]/g,''))"
用Regex限制只能輸入全形字元: onkeyup="value=value.replace(/[^uFF00-uFFFF]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^uFF00-uFFFF]/g,''))"
用Regex限制只能輸入數字:onkeyup="value=value.replace(/[^d]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^d]/g,''))"
用Regex限制只能輸入數字和英文:onkeyup="value=value.replace(/[W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^d]/g,''))"