javascript 正则表达式(抄AI生成)

3 阅读1分钟

JavaScript 中的正则表达式是一种用于匹配字符串中字符模式的工具。通过正则表达式,我们可以快速查找、替换、验证和提取文本。以下是对 JavaScript 正则表达式的介绍,包括基本语法、常用方法以及示例。

创建正则表达式

正则表达式可以通过两种方式创建:

  1. 字面量方式

    javascript
    let regex = /pattern/; // 直接使用斜杠包围模式  
    
  2. 构造函数方式

    javascript
    let regex = new RegExp('pattern'); // 使用 RegExp 构造函数  
    

基本语法

  • 字符集合:

    • [abc]:匹配 ab 或 c
    • [^abc]:匹配除了 ab 和 c 之外的任意字符。
  • 预定义字符类:

    • \d:匹配数字。
    • \D:匹配非数字。
    • \w:匹配字母、数字或下划线。
    • \W:匹配非字母数字字符。
    • \s:匹配空白字符(空格、制表符等)。
    • \S:匹配非空白字符。
    • \B:非单词边界。
    • '\b': 单词边界
    • \n:匹配换行符(LF, Line Feed)。
    • \r:匹配回车符(CR, Carriage Return)。
    • \r\n:匹配 Windows 风格的换行符。
    • [\u4e00-\u9fa5]:匹配单个中文字符。
  • 量词:

    • *:匹配 0 次或多次。
    • +:匹配 1 次或多次。
    • ?:匹配 0 次或 1 次。
    • {n}:匹配 n 次。
    • {n,}:匹配至少 n 次。
    • {n,m}:匹配 n 次到 m 次。
  • 边界:

    • ^:匹配字符串的开头。
    • $:匹配字符串的结尾。
  • 分组:

    • (abc):匹配 abc,并将其捕获为一个组。
    • (?:abc):匹配 abc,但不捕获它。

常用方法

  • test() : 测试正则表达式是否匹配某个字符串。

    javascript
    let regex = /hello/;  
    console.log(regex.test("hello world")); // 输出: true  
    
  • exec() : 执行搜索,在字符串中查找匹配。如果有匹配,返回包含匹配结果的数组;否则返回 null

    javascript
    let match = regex.exec("hello world");  
    console.log(match); // 输出: ["hello", index: 0, input: "hello world", groups: undefined]  
    
  • String.prototype.match() : 通过正则表达式在字符串中查找匹配项。

    javascript
    let str = "The quick brown fox";  
    let result = str.match(/\b\w{3}\b/g); // 匹配所有 3 个字母的单词  
    console.log(result); // 输出: ["fox"]  
    
  • String.prototype.replace() : 使用正则表达式替换字符串中的匹配内容。

    javascript
    let text = "Visit my blog at blog.com";  
    let newText = text.replace(/blog/g, "website");  
    console.log(newText); // 输出: "Visit my website at website.com"  
    
  • String.prototype.split() : 通过正则表达式分割字符串。

    javascript
    let str = "apple,banana,orange";  
    let fruits = str.split(/,/);  
    console.log(fruits); // 输出: ["apple", "banana", "orange"]  
    

正则表达式的例子

  1. 匹配电子邮件地址:

    javascript
    let emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;  
    console.log(emailRegex.test('example@example.com')); // 输出: true  
    
  2. 提取网址中的域名:

    javascript
    let urlRegex = /https?://(www.)?([a-zA-Z0-9.-]+)/;  
    let match = urlRegex.exec('https://www.example.com/pathtofile');  
    console.log(match[2]); // 输出: "example.com"  
    
  3. 验证手机号:

    javascript
    let phoneRegex = /^\d{3}-\d{3}-\d{4}$/;  
    console.log(phoneRegex.test('123-456-7890')); // 输出: true