正則表達(dá)式 | Greediness | JSON

一.正則表達(dá)式

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
  • 匹配變化的字符,在正則表達(dá)式中,用*表示任意個字符(包括0個){0,},用+表示至少一個字符{1,},用?表示0個或1個字符{0,1},用{n}表示n個字符,用{n,m}表示n到m個字符。
3.要做更精確地匹配,可以使用[](方括號)表示范圍:
  • [\w]:可以匹配一個數(shù)字、字母或者下劃線。
  • [a-zA-Z\_\$][0-9a-zA-Z\_\$]*可以匹配由字母或下劃線、$開頭,后接任意個由一個數(shù)字、字母或下劃線、$組成的字符串,也就是JavaScript允許的變量名。
4.others
  • A|B可以匹配AB
(J|j)ava(S|s)cript 可以匹配:'JavaScript'、'Javascript'、'javaScript'、'javascript'
^表示行的開始,^\d表示必須以數(shù)字開頭。
$表示行的結(jié)束,\d$表示必須以數(shù)字結(jié)束。
5.JavaScript創(chuàng)建正則表達(dá)式的兩種方式
//***/正則表達(dá)式/***
var re1 = /yyc\-007/;
re1;
>>>/yyc\-007/

//new RegExp('正則表達(dá)式')
var re2 = new RegExp('yyc\-007');
re2;
>>>/yyc-007/

var re2 = new RegExp('yyc\\-007');//注意轉(zhuǎn)義
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"]

//使用正則表達(dá)式
'a  b   c'.split(/\s+/);
>>>(3) ["a", "b", "c"]

More split():
String.prototype.split()
標(biāo)準(zhǔn)對象 | toString() | Date | split() | HTTP報文

8.分組

①是什么?用圓括號()表示的就是要提取的分組(Group)。

exec實例
exec描述
9.貪婪匹配

①是什么?匹配盡可能多的字符。

var re = /^(\d+)(0*)$/;
re.exec('10086');
>>>(3) ["10086", "10086", "", index: 0, input: "10086"]

②正則匹配默認(rèn)就是貪婪匹配。

10.全局搜索

①是什么?JavaScript的正則表達(dá)式有幾個特殊的標(biāo)志,最常用的就是g,表示全局匹配。

②還有什么特殊的標(biāo)志?i表示忽略大小寫;m表示執(zhí)行多行匹配。

③特殊標(biāo)志在正則表達(dá)式中如何表示?

var r1 = /test/g;
//等價于
var r2 = new RegExp('test','g');

④全局匹配的作用?可以多次執(zhí)行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

擴(kuò)展:Regular-Expressions.info---repeat

一.Greediness

1.是什么?

This is a <em>first</em> test.

  • 這是個字符串,我想用正則表達(dá)式匹配其中的HTML標(biāo)簽,也就是<em></em>。

  • 結(jié)果卻是這樣的:

一段.png
  • 但是我想要的結(jié)果是這樣:
我想要的結(jié)果.png
2.形成這種錯誤匹配的原因:

①第一個符號是<:這是個literal(字面量)

《.png

②第二個符號是:.dot(點)

the dot matches any character except newlines.

點.png
點實際情況.png

③第三個符號是+號(Plus)

+號效果.png

The dot is repeated by the plus. The plus is greedy. Therefore, the engine will repeat the dot as many times as it can. The dot matches e, 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是貪婪匹配的,所以點號重復(fù)執(zhí)行,也就是在剩余的字符串中不斷匹配,直至遇到換行符。然后,正則引擎才會繼續(xù)去執(zhí)行下一個符號>

④此時正則引擎執(zhí)行第四個符號:>

  • 現(xiàn)在的情況是這樣的:<.+ 已經(jīng)從字符串中匹配了<em>first</em> test. 同時正則引擎已經(jīng)執(zhí)行到達(dá)了該字符串的結(jié)尾。因此,沒有>給我們匹配了。
+號效果.png
  • 但是,正則引擎的記憶力很好,它記得返回的路,專業(yè)術(shù)語叫backtrack(回溯)。

It will reduce the repetition of the plus by one, and then continue trying the remainder of the regex.

  • 此時,.+匹配的結(jié)果為em>first</em> test(注意少了最后一個點喔),正則表達(dá)式中下一個符號仍為>,但是,字符串中的下一個字符,也就是最后一個字符是.,匹配失敗。

  • 繼續(xù)回溯,此時.+匹配的結(jié)果為em>first</em> tes,仍不匹配。直至.+匹配的結(jié)果為em>first</em,此時正則表達(dá)式的下一個字符與該字符串中的下一字符匹配。

  • 結(jié)果:

一段.png
3.那如何阻止貪婪匹配,獲得自己想要的匹配內(nèi)容呢?

①最快的解決辦法就是將貪婪匹配變成"懶蟲"模式。

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.

③"懶蟲模式"機(jī)制:

Again, < matches the first < in the string. The next token is the dot, 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 with e. The requirement has been met, and the engine continues with > and m. 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 to em, 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.

  • 首先正則表達(dá)式中的<符號匹配字符串中的<符號。第二步,正則表達(dá)式中的符號是.點(dot),因為現(xiàn)在采用"懶蟲模式",所以正則表達(dá)式引擎盡可能少的重復(fù)執(zhí)行點操作符,由于緊跟在.點(dot)后面的第三個符號是+(Plus),因此點操作符至少執(zhí)行一次。這次點操作符匹配的是e,接下來的工作是:正則表達(dá)式中的最后一個符號>與字符串中的下一個字符M匹配,匹配失敗。此時,引擎將再次回溯,只不過,這次是拓展(expand)而不是減少(reduce):.+擴(kuò)展成em,此時正則表達(dá)式中的最后一個符號>與字符串中的下一個字符>匹配,匹配成功,完事。
懶蟲模式.png

二.JSON

1.JSON:JavaScript Object Notation.
2.創(chuàng)始人:Douglas Crockford
3.JSON中的數(shù)據(jù)類型
  • number
  • boolean
  • string
  • null
  • array
  • object
4.為了統(tǒng)一解析,JSON的字符串規(guī)定必須使用雙引號"",Object的鍵也必須使用雙引號""。
5.可以將任何JavaScript對象序列化成一個JSON格式的字符串,通過網(wǎng)絡(luò)傳輸給其他計算機(jī)。接收方將其反序列化成一個JavaScript對象,就可以在JavaScript中直接使用這個對象。
6.那么如何序列化?
var Person = {
    name: 'Gerg',
    age: 21,
    sex: 'male',
    city: 'Shanghai'
};
JSON.stringify(Person);
>>>"{"name":"Gerg","age":21,"sex":"male","city":"Shanghai"}"

①這看起來也太費勁了,麻煩來點縮進(jìn):

var Person = {
    name: 'Gerg',
    age: 21,
    sex: 'male',
    city: 'Shanghai'
};
JSON.stringify(Person,null,' ');
>>>
"{
"name": "Gerg",
"age": 21,
"sex": "male",
"city": "Shanghai"
}"

②我只想知道你的名字和年齡,JSON.stringify方法的第二個參數(shù)可以滿足你的需求。

var Person = {
    name: 'Gerg',
    age: 21,
    sex: 'male',
    city: 'Shanghai'
};
JSON.stringify(Person,['name','age'],' ');
>>>
"{
"name": "Gerg",
"age": 21
}"

③還可以傳入一個函數(shù),這樣對象的每個鍵值都會被函數(shù)先處理:

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應(yīng)該序列化的數(shù)據(jù):

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()還可以接收一個函數(shù),用于改變解析后的屬性。

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}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容