您的位置:

正则匹配括号

一、正则匹配括号内容

正则匹配括号是指匹配括号内的内容,常见的括号有小括号(())、中括号([])、大括号({})等。使用正则表达式可以方便地匹配这些符号,语法为:用圆括号将需要匹配的内容括起来。

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)模式使其匹配所有括号内容。