JavaScript RegExp Group [abc]

Definition and usage

Bracket [abc] specifies the matching item within the brackets.

Square brackets can define a single character, a group, or a character range:

[abc] Any character a, b, or c.
[A-Z] Any character from uppercase A to uppercase Z.
[a-z] Any character from lowercase a to lowercase z.
[A-z] Any character from uppercase A to lowercase z.

Example

Global search for the character "h" in the string:

let text = "Is this all there is?";
let pattern = /[h]/g;

亲自试一试

Hint

Please use [^abc] Expression finds any character not inside parentheses.

Example 1

For global search of characters "i" and "s" in the string:

let text = "Do you know if this is all there is?";
let pattern = /[is]/gi;

亲自试一试

例子 2

全局搜索字符串中从小写 "a" 到小写 "h" 的字符:

let text = "Is this all there is?";
let pattern = /[a-h]/g;

亲自试一试

例子 3

全局搜索从大写 "A" 到大写 "E" 的字符范围:

let text = "I SCREAM FOR ICE CREAM!";
let pattern = /[A-E]/g;

亲自试一试

例子 4

全局搜索从大写 "A" 到小写 "e" 的字符(将搜索所有大写字母,但仅搜索从 a 到 e 的小写字母。)

let text = "I Scream For Ice Cream, is that OK?!";
let pattern = /[A-e]/g;

亲自试一试

例子 5

对字符范围 [a-s] 进行全局、不区分大小写的搜索:

let text = "I Scream For Ice Cream, is that OK?!";
let pattern = /[a-s]/gi;

亲自试一试

例子 6

对字符进行 "g" 和 "gi" 搜索:

let text = "THIS This this";
let result1 = text.match(/[THIS]/g);
let result2 = text.match(/[THIS]/gi);

亲自试一试

语法

new RegExp("[abc]")

或者简写:

/[abc]/

带修饰符的语法

new RegExp("[abc]", "g")

或者简写:

/[abc]/g

浏览器支持

/[abc]/ 是 ECMAScript1 (ES1) 特性。

所有浏览器都完全支持 ES1 (JavaScript 1997):

Chrome IE Edge Firefox Safari Opera
支持 支持 支持 支持 支持 支持

正则表达式搜索方法

在 JavaScript 中,正则表达式文本搜索可以用不同的方法完成。

使用模式(pattern)作为正则表达式,这些是最常用的方法:

ƙirarorin ƙirarorin
text.match(ƙararorin) ƙararorin ƙirarorin match()
text.search(ƙararorin) ƙararorin ƙirarorin search()
ƙararorin.exec(text) RexExp ƙararorin exec()
ƙararorin.test(text) RexExp ƙararorin ƙaɗaɗa test()