元字符

预定义类

边界

^在中括号中时,匹配非hello的

str = 'hello world'
str.match(/[^hello]/g) //[" ", "w", "r", "d"] 匹配非hello的

^不在中括号时,匹配以hello开头的

str = 'hello world'
str.match(/^hello/g) //["hello"]

$以..结尾

str = 'yeah world hello'
str.match(/hello$/g) //["hello"]
str = 'hello1 yeah world hello2 root hello3'
str.match(/hello\d/g) //["hello1", "hello2", "hello3"]
str.match(/hello\d$/g) //["hello3"]
str.match(/^hello\d/g) //["hello1"]

\b单词边界

str = 'hello1 hello2orld hello3 12-hello4-333z ccchello7'
str.match(/\bhello\d\b/g) //["hello1", "hello3", "hello4"]
str.match(/\bhello\d/g) // ["hello1", "hello2", "hello3", "hello4"]

精准判断是否在其中

str = 'header3 clearfix active header-fixed'  //判断是否有header
str.match(/\bheader\b/g) //["header"] 这里用\b其实是错误的,因为把header-fixed当成了header //应该用
str.match(/(^|\s)header($|\s)/g) //null

修改str后重新判断一次

str = 'header clearfix active header-fixed'
str.match(/(^|\s)header($|\s)/g) //["header"]

量词

 
str = 'http://github.com'
str.match(/http?:\/\/.+/g) //["http://github.com"]
 
 

+号和*号

//用+号 和 用*号
str = 'http://github.com'
str2 = 'https://github.com'
str3 = 'httpssssss://github.com' str.match(/https+:\/\/.+/g) //null 因为+必须出现一次或多次s
str.match(/https*:\/\/.+/g) //["http://github.com"] *是0次或多次,所以可以匹配
str2.match(/https*:\/\/.+/g) //["https://github.com"]
str3.match(/https*:\/\/.+/g) //["httpssssss://github.com"]
匹配是否是url的正则:
str.match(/^(https?:)?\/\/.+/g)

//测试
str = 'http://github.com'
str2 = 'https://github.com'
str3 = 'httpssssss://github.com'
str4 = '//github.com' str.match(/^(https?:)?\/\/.+/g) //["http://github.com"]
str2.match(/^(https?:)?\/\/.+/g) //["https://github.com"]
str3.match(/^(https?:)?\/\/.+/g) //null
str4.match(/^(https?:)?\/\/.+/g) //["//github.com"]
判断用户输入的是一个手机号
str.match(/^1[34578]\d{9}$/g)

//测试
str = '17300001111'
str2 = '12300001111'
str3 = 'ab100001111' str.match(/^1[34578]\d{9}$/g) //["17300001111"]
str2.match(/^1[34578]\d{9}$/g) //null
str3.match(/^1[34578]\d{9}$/g) //null

即写成函数,判断用户输入的是否是手机号:

function isPhoneNum(str) {
if(/^1[34578]\d{9}$/g.test(str)) {
console.log("是正确的手机号")
} else {
console.log("格式错误,不是正确的手机号")
}
}

贪婪模式 / 非贪婪模式

看了上面介绍的量词,比如{3,5}这个量词,要是在句子中出现了十次,那么他是每次匹配三个还是五个,反正3、4、5都满足3~5的条件

量词在默认下是尽可能多的匹配的,也就是大家常说的贪婪模式

'123456789'.match(/\d{3,5}/g);     //["12345", "6789"]

既然有贪婪模式,那么肯定会有非贪婪模式,让正则表达式尽可能少的匹配,也就是说一旦成功匹配不再继续尝试,做法很简单,在量词后加上?即可

'123456789'.match(/\d{3,5}?/g);    //["123", "456", "789"]

参考:贪婪模式/非贪婪模式之详解 (具体图文分析)

分组

有时候我们希望使用量词的时候匹配多个字符,而不是只是匹配一个,比如希望匹配evenyao出现20次的字符串,我们如果写成 evenyao{20} 的话匹配的是evenyao 中 o 出现20次

    /evenyao{20}/

怎么把evenyao作为一个整体呢?使用()就可以达到此目的,我们称为分组

    /(evenyao){20}/

var reg1 = /hello|world/
//等同于
var reg2 = /(hello)|(world)/

分组嵌套

  • 从HTML字符串中取出 URL
var str = '<a href="https://github.com">'
str.match(/href="(https?:\/\/.+?)"/) //["href="https://github.com"", "https://github.com", index: 3, input: "<a href="https://github.com">", groups: undefined]
str.match(/href="(https?:\/\/.+?)"/)[1] //https://github.com
 
 

前瞻


//even(?=yao) //匹配后面是yao的even (/even(?=yao)/).exec('evenyao123'); //['even']
(/even(?=yao)/).exec('even123yao'); //null //even(?!yao) //匹配后面不yao的even (/even(?!yao)/).exec('evenyao123'); //null
(/even(?!yao)/).exec('even123yao'); //['even']

JavaScript 正则相关函数

  • 去除字符串两边的空白字符的函数
function trim(str) {
return str.replace(/^\s*|\s*$/g,'')
} trim(' hello word ')
  • 判断用户输入的是不是合法用户名(长度6-20个字符,只能包括字母、数字、下划线)
function isValidUsername(str) {
var reg = /^\w{6,20}$/g
if(reg.test(str)) {
console.log('是合法的用户名')
} else {
console.log('不是合法的用户名')
}
} isValidUsername('evenyao') //是合法的用户名
  • 判断用户输入的是否是邮箱的函数
function isEmail(str) {
var reg = /^\w+\.?\w+@\w+(\.\w+){1,3}$/g //{1,3}是因为大多邮箱@后不会超过3个域名段,如果有这种邮箱格式,换成*即可
if(reg.test(str)) {
console.log('是正确的邮箱地址')
} else {
console.log('不是正确的邮箱地址')
}
} isEmail('17300001111@163.com') //是正确的邮箱地址
  • 判断用户输入的是否是手机号的函数
function isPhoneNum(str) {
var reg = /^1[34578]\d{9}$/g
if(reg.test(str)){
console.log('是正确的手机号格式')
} else {
console.log('不是正确的手机号格式')
}
} isPhoneNum(17300001111) //是正确的手机号格式

JavaScript 正则的方法

test

test方法用于测试字符串参数中是否存正则表达式模式,如果存在则返回true,否则返回false
上面的正则函数就是利用了test返回布尔类型做的

exec

exec方法用于正则表达式模式在字符串中运行查找,如果exec()找到了匹配的文本,则返回一个结果数组,否则返回 null

除了数组元素和length属性之外,exec()方法返回对象还包括两个属性。

  • index 属性声明的是匹配文本的第一个字符的位置
  • input 属性则存放的是被检索的字符串string
var str = '123 456 789'  //"123 456 789"
var reg = /\d{3}/
reg.exec(str)
 

用while进行exec方法

var str = '123 456 789'  //"123 456 789"
var reg = /\d{3}/g
while(result = reg.exec(str)) {
console.log(result[0]) //因为返回的是数组,所以每次取0位置的值,直到null
}
 

match

match()方法将检索字符串,以找到一个或多个与regexp匹配的文本。但regexp是否具有标志 g对结果影响很大。

非全局调用

如果regexp没有标志g,那么match()方法就只能在字符串中执行一次匹配。如果没有找到任何匹配的文本,match() 将返回null。否则它将返回一个数组,其中存放了与它找到的匹配文本有关的信息。

该数组的第一个元素存放的是匹配文本,而其余的元素存放的是与正则表达式的子表达式匹配的文本。除了这些常规的数组元素之外,返回的数组还含有两个对象属性

  • index 属性声明的是匹配文本的起始字符在字符串中的位置
  • input 属性声明的是对 stringObject 的引用

例子
var r = 'aaa123456'.match(/\d/)

全局调用

如果regexp具有标志g则match()方法将执行全局检索,找到字符串中的所有匹配子字符串

若没有找到任何匹配的子串,则返回 null。如果找到了一个或多个匹配子串,则返回一个数组

不过全局匹配返回的数组的内容与前者大不相同,它的数组元素中存放的是字符串中所有的匹配子串,而且也没有index属性或input属性。

例子
var r = 'aaa123456'.match(/\d/g)

replace

  • 去除字符串两边的空白字符
var str = '  hello world     '
str.replace(/^\s*|\s*$/g,'') //先正则匹配,再用''替换
 

split

我们经常使用split方法把字符串分割为字符数组

'a,b,c,d'.split(','); //["a", "b", "c", "d"]

和replace方法类似,在一些复杂的分割情况下我们可以使用正则表达式解决

'a1b2c3d'.split(/\d/); //["a", "b", "c", "d"]

例子:

var str = 'h  e   llo   wo   rld'   //"h  e   llo   wo   rld"
str.split(/\s*/) // ["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]
 

JavaScript 正则的更多相关文章

  1. JavaScript正则实战

    *:first-child { margin-top: 0 !important; } .markdown-body>*:last-child { margin-bottom: 0 !impor ...

  2. 我也谈javascript正则匹配

    一.javascript 正则全局匹配 g 慎用test()方法 来个例子: var a = /^[a-z]+/gi; a.test('bb123'); //true a.lastIndex ; // ...

  3. JavaScript正则式入门

    正则式 正则表达式,又称规则表达式.(英语:Regular Expression,在代码中常简写为regex.regexp或RE),计算机科学的一个概念.正则表通常被用来检索.替换那些符合某个模式(规 ...

  4. JavaScript正则中\1\2的作用

    一.示例 1. 验证6个相同的数字 var reg = new RegExp(/^(\d)\1{5}/g); var a = '333333'; if(reg.test(a)) { alert('ri ...

  5. JavaScript 正则表达收集整理

    JavaScript 正则表达收集整理 //可为空 /^\s*$/ //密码验证,必须且只含有数字和字母,可以拥有英文符号,6-17位 /(?=.{,})(?=.*\d)(?=.*[a-z])[\x2 ...

  6. JavaScript正则常用知识总结

    一.JavaScript正则相关方法 str.match(regexp)与regexp.exec(str)功能类似. str.search(regexp)与regexp.test(str)功能类似. ...

  7. JavaScript 正则的使用方法

    JavaScript正则方法 1.compile 编译一个正则表达式对象 rgExp.compile(pattern, [flags])  pattern字符串表达式 2.exec 在指定字符串中执行 ...

  8. Javascript正则构造函数与正则表达字面量&&常用正则表达式

    本文不讨论正则表达式入门,即如何使用正则匹配.讨论的是两种创建正则表达式的优劣和一些细节,最后给出一些常用正则匹配表达式. Javascript中的正则表达式也是对象,我们可以使用两种方法创建正则表达 ...

  9. JavaScript正则验证邮箱

    正则表达式/^正则$/.test() <html> <head> <title>JavaScript</title> <meta charset= ...

随机推荐

  1. 屏蔽JS代码错误

    用来屏蔽IE的错误的JS代码,也能屏蔽弹出框错误! <SCRIPT language=JavaScript> function killErrors() { return true; } ...

  2. 轻量ORM-SqlRepoEx (六) JOIN

    示例使用的是最新 SqlRepoEx 2.0.2 可在:https://github.com/AzThinker/SqlRepoEx2.0Demo 或:https://gitee.com/azthin ...

  3. MyBatis-Plus工具快速入门使用

    MyBatis-plus有什么特色 1.代码生成 2.条件构造器 对我而言,主要的目的是使用它强大的条件构建器. 快速使用步骤: 1.添加pom文件依赖 <dependency> < ...

  4. STL笔记

    STL的基本概念: 1-容器:是可容纳各种类型的数据结构,是 类模板. 2-迭代器:是用于依次存放容器中的元素,类似指针. 3-算法: 是用于操作容器中元素的 函数模板. sort() 用来对 vec ...

  5. C++ Primer 第8章作业

    练习8.1 编写函数,接受一个istream&参数,返回值类型也是istream&. 此函数须从给定流中读取数据,直至遇到文件结束标识时停止.它将读取的数据打印在标准输出上.完成这些操 ...

  6. 自己写的代码实现Session

    package com.zq.web.context.windows; import java.util.HashMap;import java.util.Map; import org.apache ...

  7. 用sqldeveloper连接数据库

    用sql developer连接sqlserver,连接窗口默认没有sqlsever页签,需要配置数据库驱动: 具体步骤: 1.工具--首选项--数据库--第三方JDBC驱动

  8. mongodb C++ Driver安装

    前言 mongocxx官网地址 http://mongocxx.org/?jmp=docs 本文的安装版本是:mongocxx-r3.2.0.tar.gz . 参考文档安装过程http://mongo ...

  9. header()函数用处

    header() 函数向客户端发送原始的 HTTP 报头. 认识到一点很重要,即必须在任何实际的输出被发送之前调用 header() 函数(在 PHP 4 以及更高的版本中,您可以使用输出缓存来解决此 ...

  10. django路由基本使用-6

    路由定义位置 django的路由是定义在 urls.py 文件下的 urlpatterns 列表中的. urls.py 文件是路由解析的入口. from django.conf.urls import ...