浅谈正则表达式

1,320 阅读5分钟

前言

在现代编程和文本处理中,正则表达式(Regular Expression,简称Regex或RegExp)是一种不可或缺的工具。它提供了一种强大而灵活的方式来搜索、匹配、替换文本。本文将简单介绍正则表达式的基本概念、语法和高级用法,以及如何在实际项目中应用它们。让我们一起深入了解这个文本处理的利器。

image.png

正则表达式的基本概念

正则表达式是一种由字符和操作符组成的字符串模式,用于匹配一系列字符串。以下是一些正则表达式的基本概念和语法:

1. 字面量字符和字符类

字面量字符直接匹配文本中的字符,而字符类使用方括号 [] 来匹配其中任意一个字符。

字面量字符用法举例:

const regexLiteral = /hello/;//匹配含有'hello'的字符

console.log(regexLiteral.test("hello world"));  // true
console.log(regexLiteral.test("hi there"));    // false

字符类用法举例:

const regexCharacterClass = /[aeiou]/;//匹配包含'aeiou'中任意一个的字符

console.log(regexCharacterClass.test("apple"));  // true
console.log(regexCharacterClass.test("banana")); // true

2. 元字符

元字符是具有特殊含义的字符,常见的元字符包括.^$*+?|等。

.       // 匹配除换行符以外的任意一个字符
^       // 匹配字符串的开始
$       // 匹配字符串的结束
\d      // 匹配任意数字(相当于 [0-9])
\w      // 匹配任意字母、数字、下划线(相当于 [a-zA-Z0-9_])
\s      // 匹配任意空白字符

元字符 .用法举例:

const regexDot = /a.b/;//

console.log(regexDot.test("acb"));  // true
console.log(regexDot.test("a\nb")); // false

元字符 ^$用法举例:

const regexStartEnd = /^hello$/;//匹配'hello',多一点少一点都不行

console.log(regexStartEnd.test("hello"));   // true
console.log(regexStartEnd.test("hello!"));  // false
console.log(regexStartEnd.test("hi hello")); // false

3. 量词

量词用于指定匹配次数,包括{n}{n,}{n,m}。量词用于指定匹配次数,例如 {n} 表示匹配恰好 n 次,{n,} 表示至少匹配 n 次,{n,m} 表示匹配次数在 n 和 m 之间。例如:

a{3}    // 匹配连续出现 3 次的字符 'a'
\d{2,4} // 匹配连续出现 2 到 4 次的数字

用法举例:

const regexQuantifier = /\d{3}/;//匹配至少连续出现三次数字的字符

console.log(regexQuantifier.test("123"));    // true
console.log(regexQuantifier.test("4567"));   // true
console.log(regexQuantifier.test("12"));     // false

4. 分组

使用圆括号()表示一个组,可以对组内的内容进行分组和捕获。例如:

(\d{3})-(\d{2})-(\d{4})   // 捕获日期中的年、月、日

用法举例:


const regexGroup = /(\d{2})-(\d{2})-(\d{4})/;

const date = "01-16-2022";
const match = date.match(regexGroup);

console.log(match[1]); // "01"
console.log(match[2]); // "16"
console.log(match[3]); // "2022"

正则表达式的高级用法

除了基本概念外,正则表达式还有一些高级用法,使其更加强大和灵活。

1. 非捕获组

除了捕获组外,还可以使用非捕获组 (?:...),这样可以进行分组而不进行捕获。

(?:\d{3})-(\d{2})-(\d{4})   // 使用非捕获组

用法举例:

const text = "apple banana cherry";
const regexNonCapturingGroup = /(?:apple|banana) (\w+)/;

const match = text.match(regexNonCapturingGroup);

console.log(match);          // 匹配结果数组
console.log(match[1]);       // "cherry"

2. 反向引用

可以使用反向引用 \1, \2 等来引用之前捕获的分组,使得可以匹配重复出现的内容。

(\w+)\s\1   // 匹配重复的单词,如 "hello hello"

用法举例:

const regexBackreference = /(\w+)\s\1/;

console.log(regexBackreference.test("hello hello"));  // true
console.log(regexBackreference.test("hi there"));     // false

3. 零宽断言

零宽断言用于在匹配字符的位置时,不消耗字符。例如,(?=...) 表示正向肯定先行断言,匹配位置后面紧跟着某内容。

\w+(?=\d)   // 匹配一个单词后面紧跟着数字的情况

正向肯定先行断言 (?=...)用法举例:

const regexPositiveLookahead = /\w+(?=\d)/;

console.log(regexPositiveLookahead.test("word123")); // true
console.log(regexPositiveLookahead.test("word"));    // false

反向否定后行断言 (?<!...)用法举例:

const regexNegativeLookbehind = /(?<!\d)\w+/;

console.log(regexNegativeLookbehind.test("word123")); // false
console.log(regexNegativeLookbehind.test("word"));    // true

4. 负向零宽断言

负向零宽断言表示在匹配位置时,其后面不应该出现某内容。例如,(?!...) 表示负向肯定先行断言。

\w+(?!\d)   // 匹配一个单词后面不跟着数字的情况

用法举例:

const regexNegativeLookahead = /\w+(?!\d)/;

console.log(regexNegativeLookahead.test("word123")); // false
console.log(regexNegativeLookahead.test("word"));    // true

在实际项目中应用正则表达式

正则表达式在实际项目中有许多应用场景。以下是一些例子:

1. 邮箱验证


const emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}\b/;

const isValidEmail = emailPattern.test("user@example.com");

2. 提取日期信息

const datePattern = /(\d{4})-(\d{2})-(\d{2})/;

const text = "今天是2022-01-16,明天是2022-01-17。";

const matches = text.matchAll(datePattern);

3. 替换文本中的URL

const urlPattern = /https?://\S+/;

const text = "请访问我的博客:https://www.example.com。";

const modifiedText = text.replace(urlPattern, "[链接]");

这些例子展示了正则表达式在实际项目中的强大应用。从验证用户输入到提取文本信息,正则表达式能够在各种场景下发挥重要作用。

多语言支持和工具

正则表达式在多种编程语言中都有广泛的支持,包括但不限于 JavaScriptPythonJavaC++ 等。在使用正则表达式时,可以根据项目需要选择合适的编程语言,并利用相应语言提供的正则表达式库或模块。

此外,许多文本编辑器和集成开发环境(IDE)也提供了正则表达式的支持。例如,Visual Studio CodeSublime TextAtom 等常用编辑器都支持使用正则表达式进行搜索和替换,极大地提高了开发者的效率。

结语

正则表达式是文本处理中的得力助手,通过深入了解其基本概念和高级用法,我们可以更加灵活地应用它来解决实际问题。尽管正则表达式在初学阶段可能显得有些晦涩,但通过实践和尝试,你将能够充分发挥它的潜力。希望本文能够帮助你更好地理解和运用正则表达式,提升你在文本处理领域的技能。


有什么说的不对的地方欢迎在评论区批评指正~

创作不易,如果觉得写的不错,动动发财的小手点个免费的赞吧!谢谢大家!

image.png