éè¯
éè¯è¡¨ç¤ºè¦å¹é çå符æè¡¨è¾¾å¼çæ°éã
å°è¯ä¸ä¸
const ghostSpeak = "booh boooooooh";
const regexpSpooky = /bo{3,}h/;
console.log(ghostSpeak.match(regexpSpooky));
// Expected output: Array ["boooooooh"]
const modifiedQuote = "[He] ha[s] to go read this novel [Alice in Wonderland].";
const regexpModifications = /\[.*?\]/g;
console.log(modifiedQuote.match(regexpModifications));
// Expected output: Array ["[He]", "[s]", "[Alice in Wonderland]"]
const regexpTooGreedy = /\[.*\]/g;
console.log(modifiedQuote.match(regexpTooGreedy));
// Expected output: Array ["[He] ha[s] to go read this novel [Alice in Wonderland]"]
ç±»å
夿³¨ï¼å¨ä¸æä¸ï¼é¡¹ä¸ä» æå个å符ï¼è¿å æ¬å符类ãç»åååå¼ç¨ã
| å符é | æä¹ |
|---|---|
x*
|
å°åé¢ç项âxâå¹é
0 æ¬¡ææ´å¤æ¬¡ãä¾å¦ï¼ |
x+
|
å°åä¸é¡¹âxâå¹é
1
æ¬¡ææ´å¤æ¬¡ãçä»·äº |
x?
|
å°åé¢ç项âxâå¹é
0 æ 1 次ãä¾å¦ï¼
妿ç«å³å¨ä»»ä½ |
x{n}
|
å
¶ä¸ânâæ¯ä¸ä¸ªéè´æ´æ°ï¼ä¸åä¸é¡¹âxâè³å°å¹é
ânâæ¬¡ãä¾å¦ï¼ |
x{n,}
|
å
¶ä¸ânâæ¯ä¸ä¸ªéè´æ´æ°ï¼ä¸åä¸é¡¹âxâè³å°å¹é
ânâæ¬¡ãä¾å¦ï¼ |
x{n,m}
|
å
¶ä¸ânâåâmâ为éè´æ´æ°ï¼å¹¶ä¸ |
|
|
é»è®¤æ
åµä¸ï¼å
|
示ä¾
>é夿¨¡å¼
const wordEndingWithAs = /\w+a+\b/;
const delicateMessage = "This is Spartaaaaaaa";
console.table(delicateMessage.match(wordEndingWithAs)); // [ "Spartaaaaaaa" ]
ç»è®¡åè¯
const singleLetterWord = /\b\w\b/g;
const notSoLongWord = /\b\w{2,6}\b/g;
const longWord = /\b\w{13,}\b/g;
const sentence = "Why do I have to learn multiplication table?";
console.table(sentence.match(singleLetterWord)); // ["I"]
console.table(sentence.match(notSoLongWord)); // [ "Why", "do", "have", "to", "learn", "table" ]
console.table(sentence.match(longWord)); // ["multiplication"]
å¯éå符
const britishText = "He asked his neighbour a favour.";
const americanText = "He asked his neighbor a favor.";
const regexpEnding = /\w+ou?r/g;
// \w+ ä¸ä¸ªå以ä¸åæ¯
// o è·é忝âoâï¼
// u? å¯è½è·é忝âuâ
// r è·é忝ârâ
console.table(britishText.match(regexpEnding));
// ["neighbour", "favour"]
console.table(americanText.match(regexpEnding));
// ["neighbor", "favor"]
贪婪å¹é ä¸é贪婪å¹é
const text = "I must be getting somewhere near the center of the earth.";
const greedyRegexp = /[\w ]+/;
// [\w ] ä¸ä¸ªæä¸åæ¯æä¸ä¸ªç©ºæ ¼
// + å¹é
䏿¬¡å以ä¸
console.log(text.match(greedyRegexp)[0]);
// "I must be getting somewhere near the center of the earth"
// å ä¹ææææ¬é½å¹é
ï¼é¤äºç¹å符ï¼
const nonGreedyRegexp = /[\w ]+?/; // 注æé®å·
console.log(text.match(nonGreedyRegexp));
// "I"
// å°½å¯è½å°çå¹é
åè§
- æ£åè¡¨è¾¾å¼æå
- å符类æå
- æè¨æå
- ç»åååå¼ç¨æå
RegExp