返回

直击核心!JS正则表达式玩转字符识别技巧

前端

开篇引语:玩转字符识别技巧,尽在JS正则表达式!

正则表达式,作为编程世界中的文本处理利器,在JavaScript中同样大放异彩。它不仅可以轻松处理各种文本匹配任务,更能灵活地识别和操作字符,是处理字符串的必备技能。

正则表达式字符匹配基础

正则表达式中的字符匹配非常灵活,既可以匹配单个字符,也可以匹配一组字符。下面列举一些常用的匹配方式:

  • 字符匹配: . 匹配任意单个字符,如/h.llo/可以匹配"hello"、"hallo"等字符串。
  • 字符组匹配: []匹配字符组中的任意一个字符,如/h[ae]llo/可以匹配"hello"和"hallo"。
  • 范围匹配: [-]匹配指定范围内的字符,如/h[a-z]llo/可以匹配所有小写字母开头的"hello"。
  • 通配符匹配: *匹配任意数量的字符,如/h.*llo/可以匹配"hello"、"helllo"、"hellllo"等。
  • 转义字符: \可以转义特殊字符的含义,如/h\\.llo/可以匹配"h.llo"。

正则表达式字符识别技巧

除了基本匹配方式外,正则表达式还提供了一些强大的字符识别技巧,可以让你轻松解决各种复杂的任务。

1. 捕获组与反向引用

捕获组可以使用()将匹配到的内容进行分组,并可以通过反向引用\n(其中n为捕获组的序号)来引用匹配到的内容。例如:

const re = /(he)(llo)/g;
const str = "hello helllo hellllo";
const matches = str.match(re);

console.log(matches); // ["hello", "he", "llo", "helllo", "he", "llo", "hellllo", "he", "llo"]

在这个例子中,(he)(llo)是两个捕获组,它们分别匹配到了"he"和"llo"。因此,matches数组中包含了所有匹配到的子串,以及捕获组匹配到的内容。

2. 命名捕获组

命名捕获组可以使用(?<name>pattern)的语法来定义,其中<name>为捕获组的名称。这样,就可以通过<name>来引用匹配到的内容。例如:

const re = /(?<prefix>he)(?<suffix>llo)/g;
const str = "hello helllo hellllo";
const matches = str.match(re);

console.log(matches); // [{"prefix": "he", "suffix": "llo"}, {"prefix": "he", "suffix": "llo"}, {"prefix": "he", "suffix": "llo"}]

在这个例子中,<prefix><suffix>是两个命名捕获组,它们分别匹配到了"he"和"llo"。因此,matches数组中包含了所有匹配到的子串,以及捕获组匹配到的内容,但这里是以对象的形式保存的。

3. 贪婪匹配与懒惰匹配

贪婪匹配会尽可能多地匹配字符,而懒惰匹配会尽可能少地匹配字符。默认情况下,正则表达式使用贪婪匹配。但可以使用?符号来启用懒惰匹配。例如:

const re1 = /.*llo/g; // 贪婪匹配
const re2 = /.*?llo/g; // 懒惰匹配

const str = "hello helllo hellllo";

console.log(str.match(re1)); // ["hello", "helllo", "hellllo"]
console.log(str.match(re2)); // ["hello", "helllo"]

在这个例子中,re1使用贪婪匹配,所以它匹配到了所有以"llo"结尾的子串。而re2使用懒惰匹配,所以它只匹配到了第一个以"llo"结尾的子串。

4. 正则表达式断言

正则表达式断言可以用来判断某个子模式是否出现在匹配到的子串中,但它本身并不消耗任何字符。断言有以下几种类型:

  • 肯定断言: ?=pattern匹配前一个子模式,但并不消耗任何字符。例如:
const re = /(?=hello)world/;

const str = "hello world";

console.log(str.match(re)); // ["world"]

在这个例子中,(?=hello)是一个肯定断言,它匹配"hello",但不消耗任何字符。因此,re只匹配到了"world"。

  • 否定断言: ?!pattern匹配前一个子模式,但并不消耗任何字符,如果前一个子模式不匹配,则匹配成功。例如:
const re = /(?!hello)world/;

const str = "world hello world";

console.log(str.match(re)); // ["world", "world"]

在这个例子中,(?!hello)是一个否定断言,它匹配前一个子模式"hello",但不消耗任何字符。由于"hello"没有出现在"world"之前,因此re匹配到了两个"world"。

正则表达式字符处理示例

1. 字符替换

正则表达式可以轻松地实现字符替换。例如,以下代码将字符串中的所有"hello"替换为"world":

const re = /hello/g;
const str = "hello world hello hello";

const newStr = str.replace(re, "world");

console.log(newStr); // "world world world"

2. 字符提取

正则表达式可以用来提取字符串中的特定字符。例如,以下代码将字符串中的所有数字提取出来:

const re = /\d+/g;
const str = "123abc456def789";

const matches = str.match(re);

console.log(matches); // ["123", "456", "789"]

3. 字符过滤

正则表达式可以用来过滤字符串中的特定字符。例如,以下代码将字符串中的所有标点符号过滤掉:

const re = /[\.,:;!?"]/g;
const str = "Hello, world! How are you?";

const newStr = str.replace(re, "");

console.log(newStr); // "Hello world How are you"

结束语

正则表达式在JavaScript中扮演着重要的角色,掌握了它可以让你在处理文本和字符串时游刃有余。当然,正则表达式还有很多其他用法,这里就不一一赘述了。如果你想了解更多,可以参考我的下一篇博文。