一、正則匹配括號內容
正則匹配括號是指匹配括號內的內容,常見的括號有小括號(())、中括號([])、大括號({})等。使用正則表達式可以方便地匹配這些符號,語法為:用圓括號將需要匹配的內容括起來。
const str = 'Hello (World)!'; const regex = /\((.*)\)/; console.log(str.match(regex)); // ["(World)!", "World"]
以上代碼中的正則表達式使用圓括號匹配小括號內的任意字符,返回的數組中第一個元素為匹配到的整個字符串,第二個元素為括號內的內容。
二、正則表達式不匹配括號內容
有些情況下,我們需要匹配括號本身,而不是其中的內容。此時可以使用轉義符(\)來轉義括號,表示匹配括號本身。例如:
const str = '5 + ( 3 * 2 ) - 9'; const regex = /\(/g; console.log(str.match(regex)); // ["(", "("]
以上代碼中,正則表達式匹配小括號,並使用全局匹配(g)模式使其匹配所有括號。返回的數組中包含了所有匹配到的小括號。
三、正則匹配括號裡面是數字
有時候需要判斷括號內是否是數字或者特定的數字,可以在正則表達式中使用\d來匹配數字。
const str = 'My student ID is (20211002).'; const regex = /\((\d+)\)/; console.log(str.match(regex)); // ["(20211002)", "20211002"]
以上代碼中,正則表達式匹配小括號內的數字,並把匹配到的數字存入數組中。
四、正則匹配括號內的內容
有時候需要匹配所有括號內的內容,包括嵌套的括號內的內容。可以使用非貪婪模式(?)來匹配。
const str = 'Color: [Red] (Size: M)'; const regex = /\[(.*?)\]|\((.*?)\)/g; console.log(str.match(regex)); // ["[Red]", "Red", "(Size: M)", "Size: M"]
以上代碼中,正則表達式使用非貪婪模式匹配中括號或小括號內的內容,匹配到嵌套的括號內的內容時也可以被匹配到。
五、正則匹配括號中間的字
有時候需要匹配兩個括號之間的內容,這可以通過在正則表達式中使用“不包含”符號(^)實現。
const str = 'My name is (Mike) and (1990-)year-old.'; const regex = /\(([^)]*)\)/g; console.log(str.match(regex)); // ["(Mike)", "(1990-)"]
以上代碼中正則表達式匹配小括號,使用“不包含”符號匹配小括號內的所有字符,直到遇到右括號停止。
六、正則表達式怎麼匹配方括號
匹配方括號和括號的方法與匹配小括號和中括號類似,只需要用方括號包裹字符即可。
const str = 'My favorite fruits are [apple], [banana], and [orange].'; const regex = /\[(.*?)\]/g; console.log(str.match(regex)); // ["[apple]", "[banana]", "[orange]"]
七、正則匹配括號裡面的內容
匹配括號內的內容的方法已在上述幾個小節中介紹過了,這裡再次給出完整代碼示例:
const str = 'My student ID is (20211002).'; const regex = /\((.*?)\)/; console.log(str.match(regex)); // ["(20211002)", "20211002"]
八、正則匹配中括號
匹配中括號的方法與匹配其他括號類似,只需要用中括號包裹字符即可。
const str = 'JavaScript versions: ES5, ES6, ES7.'; const regex = /\[(.*?)\]/g; console.log(str.match(regex)); // []
以上代碼中正則表達式匹配中括號內的所有字符,但返回的數組為空,因為字符串中沒有中括號。
九、正則表達式匹配括號的內容
匹配括號的內容的方法已在上述幾個小節中介紹過了,這裡再次給出完整代碼示例:
const str = 'Hello [World]!'; const regex = /\[(.*?)\]/; console.log(str.match(regex)); // ["[World]", "World"]
十、正則表達式匹配括號選取
在正則表達式中,可以使用“|”符號來匹配多個表達式。可以使用該方法來匹配多種括號。
const str = 'There are (3) [apples], (2) [bananas], and (1) [orange].'; const regex = /\((.*?)\)|\[(.*?)\]/g; console.log(str.match(regex)); // ["(3)", "[apples]", "(2)", "[bananas]", "(1)", "[orange]"]
以上代碼中正則表達式使用“|”符號匹配小括號和中括號內的內容,並使用全局匹配(g)模式使其匹配所有括號內容。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/237807.html