博客
关于我
JavaScript RegExp 对象
阅读量:206 次
发布时间:2019-02-28

本文共 1311 字,大约阅读时间需要 4 分钟。

正则表达式(RegExp)参考手册

什么是正则表达式

正则表达式是描述字符模式的工具,用于匹配特定文本内容。在检索或操作文本时,可以通过定义模式来描述要匹配的内容。简单模式可以是单个字符,而复杂模式可以包含多种字符和规则,用于解析、格式检查、替换等操作。

正则表达式的语法

正则表达式通常通过以下方式创建:```javascriptvar patt = new RegExp(pattern, modifiers);```或者更简洁地:```javascriptvar patt = /pattern(modifiers)/;```其中,`pattern`描述了匹配模式,`modifiers`是可选的修饰符,用于控制匹配行为。

常见修饰符

- `i`:忽略大小写,执行不区分大小写的匹配。- `g`:全局匹配,查找所有匹配而非仅首次匹配。

创建正则表达式的注意事项

在构造函数创建正则表达式对象时,需注意字符转义,通常在前面加上反斜杠(`\`)。例如:```javascriptvar re = new RegExp("\\w+"); // 和 /\\w+/ 等效```

实例:不区分大小写匹配 "runoob"

```javascriptvar str = "Visit RUnoob";var patt1 = /runoob/i;```输出结果:"Visit RUnoob" 中找到 "RUnoob",匹配结果为 "RUnoob"。

实例:全局匹配 "is"

```javascriptvar str = "Is this all there is?";var patt2 = /is/g;```输出结果:"Is th is all there is?",匹配结果为 "is" 和 "is"。

实例:结合全局和不区分大小写匹配 "is"

```javascriptvar str = "Is this all there is?";var patt3 = /is/gi;```输出结果:"Is th is all there is?",匹配结果为 "is"、"is"。

test() 方法

test() 方法用于测试字符串是否包含指定的值,返回布尔值。```javascriptvar str = "The best things in life are free";var re = new RegExp("e");re.test(str); // 返回 true```

exec() 方法

exec() 方法用于执行搜索,并返回找到的值或 null。```javascriptvar str = "The best things in life are free";var re = new RegExp("e");re.exec(str); // 返回 "e"```

注意事项

- 在构造函数创建正则表达式对象时,需注意字符转义。- 使用 test() 和 exec() 方法时,可结合正则表达式修饰符来控制匹配行为。

以上内容可根据实际需求进行扩展和调整,建议结合具体业务场景优化正则表达式模式和修饰符使用。

转载地址:http://enes.baihongyu.com/

你可能感兴趣的文章
NLP问答系统:使用 Deepset SQUAD 和 SQuAD v2 度量评估
查看>>
NLP:使用 SciKit Learn 的文本矢量化方法
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>