In this article
試してみましょう
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 文字