一.正則表達式
1.精確匹配:直接給出字符。
①\d:(digits)匹配[0-9]
②\w:(word character)匹配 [a-zA-Z0-9_]
,注意下劃線喔。
③\s:(whitespace character)匹配(空格),
Tab
,Carriage Return
(回車),new line
(換行),form feed
(換頁)。
2.Limiting Repetition
- 匹配變化的字符,在正則表達式中,用
*
表示任意個字符(包括0個){0,}
,用+
表示至少一個字符{1,}
,用?
表示0個或1個字符{0,1}
,用{n}
表示n個字符,用{n,m}
表示n到m個字符。
3.要做更精確地匹配,可以使用[]
(方括號)表示范圍:
-
[\w]
:可以匹配一個數字、字母或者下劃線。 -
[a-zA-Z\_\$][0-9a-zA-Z\_\$]*
可以匹配由字母或下劃線、$開頭,后接任意個由一個數字、字母或下劃線、$組成的字符串,也就是JavaScript允許的變量名。
4.others
-
A|B
可以匹配A
或B
(J|j)ava(S|s)cript 可以匹配:'JavaScript'、'Javascript'、'javaScript'、'javascript'
^表示行的開始,^\d表示必須以數字開頭。
$表示行的結束,\d$表示必須以數字結束。
5.JavaScript創建正則表達式的兩種方式
//***/正則表達式/***
var re1 = /yyc\-007/;
re1;
>>>/yyc\-007/
//new RegExp('正則表達式')
var re2 = new RegExp('yyc\-007');
re2;
>>>/yyc-007/
var re2 = new RegExp('yyc\\-007');//注意轉義
re2;
>>>/yyc\-007/
6.判斷給定的字符串是否符合條件,可使用test()
var re = /^\d{3}\-\d{3,8}$/;
re.test('123-12345678');
>>>true
re.test('123-123456789');
>>>false
7.切分字符串
//a-b之間兩個空格,b-c之間三個空格
'a b c'.split(' ');
>>>(6) ["a", "", "b", "", "", "c"]
//使用正則表達式
'a b c'.split(/\s+/);
>>>(3) ["a", "b", "c"]
More split():
String.prototype.split()
標準對象 | toString() | Date | split() | HTTP報文
8.分組
①是什么?用圓括號()
表示的就是要提取的分組(Group)。
9.貪婪匹配
①是什么?匹配盡可能多的字符。
var re = /^(\d+)(0*)$/;
re.exec('10086');
>>>(3) ["10086", "10086", "", index: 0, input: "10086"]
②正則匹配默認就是貪婪匹配。
10.全局搜索
①是什么?JavaScript的正則表達式有幾個特殊的標志,最常用的就是g
,表示全局匹配。
②還有什么特殊的標志?i
表示忽略大小寫;m
表示執行多行匹配。
③特殊標志在正則表達式中如何表示?
var r1 = /test/g;
//等價于
var r2 = new RegExp('test','g');
④全局匹配的作用?可以多次執行exec()
來搜索一個匹配的字符串。
var s = 'JavaScript, VBScript, CoffeeScript and ECMAScript';
var re = /[a-zA-Z]+Script/g;
re.exec(s);
>>>["JavaScript", index: 0, input: "JavaScript, VBScript,
CoffeeScript and ECMAScript"]
re.exec(s);
>>>["VBScript", index: 12, input: "JavaScript, VBScript,
CoffeeScript and ECMAScript"]
re.exec(s);
>>>["CoffeeScript", index: 22, input: "JavaScript, VBScript,
CoffeeScript and ECMAScript"]
re.exec(s);
>>>["ECMAScript", index: 39, input: "JavaScript, VBScript,
CoffeeScript and ECMAScript"]
re.exec(s);
>>>null
擴展:Regular-Expressions.info---repeat
一.Greediness
1.是什么?
This is a <em>first</em> test.
這是個字符串,我想用正則表達式匹配其中的HTML標簽,也就是
<em>
和</em>
。結果卻是這樣的:
- 但是我想要的結果是這樣:
2.形成這種錯誤匹配的原因:
①第一個符號是<
:這是個literal(字面量)
②第二個符號是:.
dot(點)
the dot matches any character except newlines.
③第三個符號是+
號(Plus)
The
dot
is repeated by theplus
. The plus is greedy. Therefore, the engine will repeat thedot
as many times as it can. The dot matchese
, so the regex continues to try to match the dot with the next character.m
is matched, and the dot is repeated once more. The next character is the>
. You should see the problem by now. The dot matches the>
, and the engine continues repeating the dot. The dot will match all remaining characters in the string. The dot fails when the engine has reached the void after the end of the string. Only at this point does the regex engine continue with the next token:>
.
由于點(dot)后面緊緊跟隨著加號(Plus),而Plus是貪婪匹配的,所以點號重復執行,也就是在剩余的字符串中不斷匹配,直至遇到換行符。然后,正則引擎才會繼續去執行下一個符號>
。
④此時正則引擎執行第四個符號:>
- 現在的情況是這樣的:
<.+
已經從字符串中匹配了<em>first</em> test.
同時正則引擎已經執行到達了該字符串的結尾。因此,沒有>
給我們匹配了。
- 但是,正則引擎的記憶力很好,它記得返回的路,專業術語叫backtrack(回溯)。
It will reduce the repetition of the plus by one, and then continue trying the remainder of the regex.
此時,
.+
匹配的結果為em>first</em> test
(注意少了最后一個點喔),正則表達式中下一個符號仍為>
,但是,字符串中的下一個字符,也就是最后一個字符是.
,匹配失敗。繼續回溯,此時
.+
匹配的結果為em>first</em> tes
,仍不匹配。直至.+
匹配的結果為em>first</em
,此時正則表達式的下一個字符與該字符串中的下一字符匹配。結果:
3.那如何阻止貪婪匹配,獲得自己想要的匹配內容呢?
①最快的解決辦法就是將貪婪匹配變成"懶蟲"模式。
The quick fix to this problem is to make the plus lazy instead of greedy.
②如何變成"懶蟲"模式呢?
You can do that by putting a question mark
?
after the plus+
in the regex. You can do the same with the star*
, the curly braces{}
and the question mark?
itself.
③"懶蟲模式"機制:
Again,
<
matches the first<
in the string. The next token is thedot
, this time repeated by a lazy plus. This tells the regex engine to repeat the dot as few times as possible. The minimum is one. So the engine matches the dot withe
. The requirement has been met, and the engine continues with>
andm
. This fails. Again, the engine will backtrack. But this time, the backtracking will force the lazy plus to expand rather than reduce its reach. So the match of.+
is expanded toem
, and the engine tries again to continue with>.
Now,>
is matched successfully. The last token in the regex has been matched. The engine reports that<em>
has been successfully matched.
- 首先正則表達式中的
<
符號匹配字符串中的<
符號。第二步,正則表達式中的符號是.
點(dot),因為現在采用"懶蟲模式",所以正則表達式引擎盡可能少的重復執行點操作符,由于緊跟在.
點(dot)后面的第三個符號是+
(Plus),因此點操作符至少執行一次。這次點操作符匹配的是e
,接下來的工作是:正則表達式中的最后一個符號>
與字符串中的下一個字符M
匹配,匹配失敗。此時,引擎將再次回溯,只不過,這次是拓展(expand)而不是減少(reduce):.+
擴展成em
,此時正則表達式中的最后一個符號>
與字符串中的下一個字符>
匹配,匹配成功,完事。
二.JSON
1.JSON:JavaScript Object Notation.
2.創始人:Douglas Crockford
3.JSON中的數據類型
- number
- boolean
- string
- null
- array
- object
4.為了統一解析,JSON的字符串規定必須使用雙引號""
,Object的鍵也必須使用雙引號""
。
5.可以將任何JavaScript對象序列化成一個JSON格式的字符串,通過網絡傳輸給其他計算機。接收方將其反序列化成一個JavaScript對象,就可以在JavaScript中直接使用這個對象。
6.那么如何序列化?
var Person = {
name: 'Gerg',
age: 21,
sex: 'male',
city: 'Shanghai'
};
JSON.stringify(Person);
>>>"{"name":"Gerg","age":21,"sex":"male","city":"Shanghai"}"
①這看起來也太費勁了,麻煩來點縮進:
var Person = {
name: 'Gerg',
age: 21,
sex: 'male',
city: 'Shanghai'
};
JSON.stringify(Person,null,' ');
>>>
"{
"name": "Gerg",
"age": 21,
"sex": "male",
"city": "Shanghai"
}"
②我只想知道你的名字和年齡,JSON.stringify方法
的第二個參數可以滿足你的需求。
var Person = {
name: 'Gerg',
age: 21,
sex: 'male',
city: 'Shanghai'
};
JSON.stringify(Person,['name','age'],' ');
>>>
"{
"name": "Gerg",
"age": 21
}"
③還可以傳入一個函數,這樣對象的每個鍵值都會被函數先處理:
var Person = {
name: 'Gerg',
age: 21,
sex: 'male',
city: 'Shanghai'
};
function convert(key,value){
if(typeof value === 'string'){
return value.toUpperCase();
}
return value;
}
JSON.stringify(Person,convert,' ');
>>>
"{
"name": "GERG",
"age": 21,
"sex": "MALE",
"city": "SHANGHAI"
}"
④如果還想精確控制如何序列化Person對象,可以給Person對象定義一個toJSON()
的方法,直接返回JSON應該序列化的數據:
var Person = {
name: 'Gerg',
age: 21,
sex: 'male',
city: 'Shanghai',
toJSON: function(){
return {
'Name': this.name,
'Age': this.age
};
}
};
JSON.stringify(Person);
>>>"{"Name":"Gerg","Age":21}"
7.那么又如何反序列化?
①對于一個JSON格式的字符串,可直接使用JSON.parse()
解析成一個JavaScript對象:
var Person = {
name: 'Gerg',
age: 21,
sex: 'male',
city: 'Shanghai',
};
var JSON1 = JSON.stringify(Person,['name','age']);
JSON1;
>>>"{"name":"Gerg","age":21}"
var JSON1ToObj1 = JSON.parse(JSON1);
JSON1ToObj1;
>>>{name: "Gerg", age: 21}
②JSON.parse()還可以接收一個函數,用于改變解析后的屬性。
var Person = {
name: 'Gerg',
age: 21,
sex: 'male',
city: 'Shanghai',
};
var JSON1 = JSON.stringify(Person,['name','age']);
JSON1;
>>>"{"name":"Gerg","age":21}"
var JSON1ToObj1 = JSON.parse(JSON1,function(key,value){
if(key === 'name'){
return 'Hello ' + value;
}
if(key === 'age'){
return value*2;
}
return value;
});
JSON1ToObj1;
>>>{name: "Hello Gerg", age: 42}