æ°éå
æ°éåã¯ãä¸è´ãããæåãå¼ã®æ°ã示ãã¾ãã
試ãã¦ã¿ã¾ããã
const ghostSpeak = "booh boooooooh";
const regexpSpooky = /bo{3,}h/;
console.log(ghostSpeak.match(regexpSpooky));
// äºæ³ãããçµæ: Array ["boooooooh"]
const modifiedQuote = "[He] ha[s] to go read this novel [Alice in Wonderland].";
const regexpModifications = /\[.*?\]/g;
console.log(modifiedQuote.match(regexpModifications));
// äºæ³ãããçµæ: Array ["[He]", "[s]", "[Alice in Wonderland]"]
const regexpTooGreedy = /\[.*\]/g;
console.log(modifiedQuote.match(regexpTooGreedy));
// äºæ³ãããçµæ: 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" ã¯éè² ã®æ´æ°ã§ã |
|
|
æ¢å®ã§ã¯
|
ä¾
>ç¹°ãè¿ããã¿ã¼ã³
ãã®ä¾ã§ã¯ã1 ã¤ä»¥ä¸ã®è±æ°æåã \w+ ã§ã次㫠1 ã¤ä»¥ä¸ã®æå "a" ã a+ ã§ãæå¾ã«åèªã®å¢çã \b ã§ç
§åãã¾ãã
const wordEndingWithAs = /\w+a+\b/;
const delicateMessage = "This is Spartaaaaaaa";
console.table(delicateMessage.match(wordEndingWithAs)); // [ "Spartaaaaaaa" ]
æåæ°ã®ã«ã¦ã³ã
ãã®ä¾ã§ã¯ã 1 æåã ãã®åèªã 2 æåä»¥ä¸ 6 æå以ä¸ã®åèªã 13 æå以ä¸ã®åèªãæ¤ç´¢ãã¾ãã
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"]
çç¥å¯è½ãªæå
ãã®ä¾ã§ã¯ã "our" ã¾ã㯠"or" ã§çµããåèªãæ¤ç´¢ãã¾ãã
const britishText = "He asked his neighbour a favour.";
const americanText = "He asked his neighbor a favor.";
const regexpEnding = /\w+ou?r/g;
// \w+ 1 ã¤ä»¥ä¸ã®æå
// o "o" ãç¶ã
// u? çç¥å¯è½ã§ "u" ãç¶ã
// r "r" ãç¶ã
console.table(britishText.match(regexpEnding));
// ["neighbour", "favour"]
console.table(americanText.match(regexpEnding));
// ["neighbor", "favor"]
貪欲ã¨é貪欲
ãã®ä¾ã§ã¯ã 1 ã¤ä»¥ä¸ã®åèªæåã¾ãã¯ç©ºç½æåã [\w ]+ 㨠[\w ]+? ã§æ¤ç´¢ãã¾ãã 1 ã¤ç®ã¯è²ªæ¬²ã§ã 2 ã¤ç®ã¯è²ªæ¬²ã§ã¯ããã¾ããã 2 ã¤ç®ã¯æå°è¦ä»¶ãæºããã¨ããã«åæ¢ãããã¨ã«æ³¨æãã¦ãã ããã
const text = "I must be getting somewhere near the center of the earth.";
const greedyRegexp = /[\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"
// ä¸è´ããç®æã¯åãããæãçã 1 æå
é¢é£æ å ±
- æ£è¦è¡¨ç¾ã¬ã¤ã
- æåã¯ã©ã¹ã¬ã¤ã
- ã¢ãµã¼ã·ã§ã³ã¬ã¤ã
- ã°ã«ã¼ãã¨å¾æ¹åç §
RegExp- æ£è¦è¡¨ç¾ãªãã¡ã¬ã³ã¹
- æ°éå:
*,+,?,{n},{n,},{n,m}