每次想學習正則表達式看到給個表讓去背誦并思,就放棄了钥勋,這次從一個實例來學習并在線驗證羊赵。
先給出一個天氣預報接口返回數(shù)據(jù)
{"reason":"查詢成功!","result":{"city":"上海","realtime":{"temperature":"26","humidity":"94","info":"晴","wid":"00","direct":"北風","power":"0級","aqi":"65"},"future":[{"date":"2019-09-10","temperature":"25\/32℃","weather":"多云","wid":{"day":"01","night":"01"},"direct":"南風轉(zhuǎn)東南風"},{"date":"2019-09-11","temperature":"25\/32℃","weather":"陰轉(zhuǎn)多云","wid":{"day":"02","night":"01"},"direct":"東北風轉(zhuǎn)東南風"},{"date":"2019-09-12","temperature":"25\/31℃","weather":"陰轉(zhuǎn)多云","wid":{"day":"02","night":"01"},"direct":"東風轉(zhuǎn)東南風"},{"date":"2019-09-13","temperature":"24\/31℃","weather":"多云","wid":{"day":"01","night":"01"},"direct":"東南風轉(zhuǎn)東風"},{"date":"2019-09-14","temperature":"24\/29℃","weather":"小雨轉(zhuǎn)多云","wid":{"day":"07","night":"01"},"direct":"東北風"}]},"error_code":0}
示例一:
匹配出最低溫度
正則表達式:
temperature":"[\d]{0,2}[\W]{2}[\d]{0,2}
正則表達式講解:
此表達式的意思是:匹配含有(temperature":"+零到兩位數(shù)字+零到兩位特殊字符+零到兩位數(shù)字+℃)的字符串
'\d'? 用來匹配數(shù)字
{0,2} 表示[ ]內(nèi)的字符長度
\w 表示英文字母和數(shù)字和下劃線[A-Za-z0-9_]]
\W非字母和數(shù)字
匹配結(jié)果:
'temperature":"25\/32℃',
'temperature":"25\/32℃',
'temperature":"25\/31℃',
'temperature":"24\/31℃',
'temperature":"24\/29℃'
示例二:
匹配風向
正則表達式:
direct":"[\u4e00-\u9fa5]{3,10}"
此表達式的意思是:匹配包含"direct":"+三到十個漢字的字符串"
?\u4e00-\u9fa5 :匹配中文字符
{3,10} :表示[ ]中字符長度為3到10
匹配結(jié)果:
direct":"南風轉(zhuǎn)東南風"
direct":"東北風轉(zhuǎn)東南風"
direct":"東風轉(zhuǎn)東南風"
direct":"東南風轉(zhuǎn)東風"
direct":"東北風"
但是如果我們這么寫表達式:direct":"[\u4e00-\u9fa5]{3,10}? 得到的結(jié)果將是:
direct":"南風轉(zhuǎn)
direct":"東北風
direct":"東風轉(zhuǎn)
direct":"東南風
direct":"東北風
為什么呢?
這里的問號相當于表明{3,10}里面匹配最小值(即匹配3位),也就是匹配3位,不加問號則是匹配到最大值(即有多少匹配多少,超過10位,則匹配10位)
以上使用正則表達式進行了匹配,下面對常用正則語法做個總結(jié)
'\d'? 用來匹配數(shù)字
\w 表示英文字母和數(shù)字和下劃線[A-Za-z0-9_]]
\W非字母和數(shù)字
\u4e00-\u9fa5 :匹配中文字符
{} 限定字符長度 客税,可以是個范圍蹈胡,也可以是具體的一個值
. :匹配除換行符(\n)外的其他所有字符
*:匹配前面的表達式0次或者n次
^:從字符串開頭匹配
$:從字符串結(jié)尾匹配
|:多項之間選擇一個??
(str):小括號里面的字符是且的關系,所以會匹配到所以‘str’
[str]:中括號里面的字符是或的關系审残,所以會匹配到所有 ‘s’或 ‘t’ 或 ‘r’