在 JavaScript 中,正则表达式(Regular Expressions, regex)是一种模式,用于匹配字符串中的字符组合。正则表达式可以使用两种方式创建:使用正则表达式字面量或使用 RegExp
构造函数。
以下是一些常见的用法和示例:
1. 使用正则表达式字面量
正则表达式字面量包含在两条斜杠之间,例如 /pattern/flags
。
| |
| let regex = /abc/; |
| |
| |
| let str = "abcdef"; |
| let result = regex.test(str); |
| console.log(result); |
2. 使用 RegExp
构造函数
你可以使用 RegExp
构造函数来创建正则表达式,这对于动态创建正则表达式非常有用。
| |
| let regex = new RegExp("abc"); |
| |
| |
| let str = "abcdef"; |
| let result = regex.test(str); |
| console.log(result); |
3. 常见的方法
test
:测试字符串是否匹配正则表达式。返回布尔值。
exec
:执行正则表达式匹配,返回匹配结果数组或 null
。
match
:字符串方法,返回匹配结果数组或 null
。
replace
:字符串方法,返回替换后的新字符串。
split
:字符串方法,使用正则表达式分割字符串。
test
示例
| let regex = /hello/; |
| console.log(regex.test("hello world")); |
| console.log(regex.test("world")); |
exec
示例
| let regex = /hello/; |
| let result = regex.exec("hello world"); |
| console.log(result); |
match
示例
| let str = "hello world"; |
| let matches = str.match(/hello/); |
| console.log(matches); |
replace
示例
| let str = "hello world"; |
| let newStr = str.replace(/world/, "there"); |
| console.log(newStr); |
split
示例
| let str = "one, two, three, four"; |
| let parts = str.split(/, /); |
| console.log(parts); |
4. 使用正则表达式标志(flags)
正则表达式标志用于控制搜索行为。常见的标志包括:
示例:忽略大小写
| let regex = /hello/i; |
| console.log(regex.test("Hello world")); |
示例:全局搜索
| let str = "hello hello hello"; |
| let matches = str.match(/hello/g); |
| console.log(matches); |
示例:多行搜索
| let str = "hello\nworld"; |
| let regex = /^world/m; |
| console.log(regex.test(str)); |
通过正则表达式,你可以在字符串中执行复杂的搜索、替换和分割操作。掌握正则表达式可以极大地提高你处理文本的能力。
本文作者:Jikefan
本文链接:https://www.cnblogs.com/jikefan/articles/18248089
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix