Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 正则match

作者:昨夜的风   发布日期:2025-07-12   浏览:101

// 示例代码:使用正则表达式 match 方法

const str = "Hello, my email is example@example.com and my phone number is 123-456-7890.";
const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
const phoneRegex = /\d{3}-\d{3}-\d{4}/g;

// 使用 match 方法查找所有匹配的邮箱地址
const emails = str.match(emailRegex);
console.log("匹配到的邮箱地址:", emails); // 输出: ["example@example.com"]

// 使用 match 方法查找所有匹配的电话号码
const phones = str.match(phoneRegex);
console.log("匹配到的电话号码:", phones); // 输出: ["123-456-7890"]

// 如果没有匹配项,match 方法会返回 null
const noMatch = "This string has no matches.".match(/xyz/);
console.log("没有匹配项时返回:", noMatch); // 输出: null

解释说明:

  1. str.match(regex)match 方法用于在字符串中搜索与正则表达式匹配的内容。如果找到匹配项,则返回一个包含所有匹配结果的数组;如果没有找到匹配项,则返回 null
  2. 正则表达式
    • emailRegex:用于匹配常见的电子邮件格式。
    • phoneRegex:用于匹配美国标准的电话号码格式(如 123-456-7890)。
  3. 全局标志 g:表示在整个字符串中查找所有匹配项,而不仅仅是第一个匹配项。
  4. 输出结果:通过 console.log 打印出匹配到的结果。

上一篇:js map类型数据

下一篇:js gzip

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 点击空白区域触发事件

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站