一、RegExp輸出的方式:
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions
二、match()的用法的延伸
延續昨日主題,match()的用法。
Return value:
const text = "Hello, World! Hello, Universe!";
const pattern = /Hello/g;
const result = text.match(pattern);
console.log(result); //["Hello","Hello"] 回傳所有匹配
const text = "Hello, World! Hello, Universe!";
const pattern = /Hello/;
const result = text.match(pattern);
console.log(result); //["Hello"] 只會回傳符合的第一個匹配
\d
匹配任何數字(0-9)的正規表達式(\d{2})
是第一個capturing group(\d{2})
是第二個capturing group(\d{4})
是第三個capturing groupconst text= "Today is 01-12-2023, and tomorrow is 02-12-2023.";
const regex = /(\d{2})-(\d{2})-(\d{4})/;
const result = text.match(regex);
console.log(result);
//["01-12-2023","01","12","2023"] 只回傳第一個匹配結果
// "01" 第一個capturing group,表示天
// "12" 第二個capturing group,表示月
//"2023" 第三個capturing group,表示年
//上一題,加上使用g
const text = 'Today is 01-12-2023, and tomorrow is 02-12-2023.';
const regex = /(\d{2})-(\d{2})-(\d{4})/g;
const result = text.match(regex);
console.log(result); //["01-12-2023","02-12-2023"] 回傳兩種結果
三、對於match()用法的描述:
String.prototype.match() 用法是非常簡單的,其實就是第一個參數使用symbol.match()方法。實際上以RegExp.prototype[@@match]()
來實現。
const str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const regexp = /[A-E]/gi;
const matches = str.match(regexp);
console.log(matches);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
const paragraph = "The quick brown fox jumps over the lazy dog. It barked.";
const capturingRegex = /(?<animal>fox|cat) jumps over/;
const found = paragraph.match(capturingRegex);
console.log(found.groups); // {animal: "fox"}
const str = "Hmm, this is interesting.";
str.match({
[Symbol.match](str) {
return ["Yes, it's interesting."];
},
}); // returns ["Yes, it's interesting."]
.
符號,代表任何文字、字母、數字、符號都可以匹配,所以有結果可回傳console.log("123".match("1.3")); // [ "123" ]