博客
关于我
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/

你可能感兴趣的文章
no connection could be made because the target machine actively refused it.问题解决
查看>>
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‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
Node JS: < 一> 初识Node JS
查看>>