匹配、搜索、替换或拆分字符串。
- 匹配特定字符
如果你想匹配一个特定的字符,你可以直接将该字符放在正则表达式中。例如,要匹配字符"a",可以使用正则表达式 /a/
。
javascript复制代码
let regex = /a/;
console.log(regex.test('a')); // 输出: true
console.log(regex.test('b')); // 输出: false
- 匹配一次或多次字符
如果你想匹配一个字符一次或多次,你可以使用 *
符号。例如,要匹配 "hello" 这个字符串,可以使用正则表达式 /hello/
。
javascript复制代码
let regex = /hello/;
console.log(regex.test('hello')); // 输出: true
console.log(regex.test('helloworld')); // 输出: false
- 匹配特定字符集合
你可以使用 []
符号来匹配一个字符集合。例如,要匹配任何小写字母,可以使用正则表达式 /[a-z]/
。
javascript复制代码
let regex = /[a-z]/;
console.log(regex.test('a')); // 输出: true
console.log(regex.test('1')); // 输出: false
- 匹配开头和结尾
如果你想匹配一个字符串的开头或结尾,你可以使用 ^
和 $
符号。例如,要匹配以 "js" 开头的字符串,可以使用正则表达式 /^js/
。
javascript复制代码
let regex = /^js/;
console.log(regex.test('jsample')); // 输出: true
console.log(regex.test('sjsample')); // 输出: false
- 分组和引用
你可以使用 ()
来分组正则表达式,并且使用 \n
来引用前面的分组。例如,要匹配 "javascript",可以使用正则表达式 /javascript/
。
javascript复制代码
let regex = /javascript/;
console.log(regex.test('I am learning javascript')); // 输出: true