第五章(3):正则表达式

正则表达式

正则表达式,又称正规表示式、正规表示法、正规表达式、规则表达式、常规表示法(英语:Regular Expression,在代码中常简写为regex、regexp或RE),是计算机科学的一个概念。正则表达式使用单个字符串来描述、匹配一系列匹配某个句法规则的字符串。在很多文本编辑器里,正则表达式通常被用来检索、替换那些匹配某个模式的文本。

ECMAScript通过RegExp类型来支持正则表达式。

创建正则表达式

创建正则表达式有两种方式。通过构造函数和字面量的方式。如下:

var reg = /hello/ // 字面量
var regexp = new RegExp("hello")  // 构造函数
元字符

元字符包括: ( [ { \ ^ $ * + ? . | } ] )。这些字符在正则中有特殊的用途。如果要匹配的字符串中包括这些符号的话,必须通过 \ 来转义。例如:

var pattern = /[a-z]/
var pattern1 = /\[a-z\]/
console.log(pattern.exec('adf'))    // ["a", index: 0, input: "adf"]
console.log(pattern1.exec('adf'))   // null

console.log(pattern.exec('[a-z]'))  // ["[a-z]", index: 0, input: "[a-z]"]
console.log(pattern1.exec('adf')) // null
正则表达式的标识
  1. g 全局模式
var regG = /m/g
console.log(('my name is Test').match(regG))  // ["m", "m"]
console.log(regG.exec('my name is Test')) // ["m", index: 0, input: "my name is Test"]
  1. i 不区分大小写
// i 不区分大小写
var regI = /h/i
console.log(regI.test('He'))  // true
正则表达式的方法
  1. test
// test 测试字符串是否匹配正则表达式,返回true或者false
var reg = /^(\d{3}-\d{4}-\d{4})$/
console.log(reg.test('187-0127-9074'))  // true
console.log(reg.test('187-0127-90745asd'))  // true
  1. replace
// replace 字符串中执行查找匹配的String方法,并且使用替换字符串替换掉匹配到的子字符串。
var strRe = ("187-0127-9074").replace(reg, '电话号码')
console.log(strRe)  // 电话号码
  1. exec和match

exec和match有些类似。exec是正则表达式的方法,match是字符串的方法。exec和match都会返回数组。但是在使用g标志的时候,match会返回一个数组,包括所有匹配的字符串。而exec只会返回第一个匹配的字符。

exec返回包含一个匹配信息的数组,如果没有匹配则返回null。数组是Array的实例。包含额外两个属性:index和input。index表示匹配的字符串的索引值,input表示应用正则的字符串。数组中的第一项是匹配的字符串,第二项至第N项是捕获括号中对应的字符串的值。如果没有捕获括号,则只有第一项。match在不带g标识的时候表现和exec类似。

exec

// exec 在字符串中查找是否匹配,返回一个数组。找不到则返回null.
var reg = /^(\d{3}-\d{4}-\d{4})$/
console.log(reg.exec('187-0127-9074187-0127-9074')) // null
console.log(reg.exec('187-0127-9074'))  // ["187-0127-9074", "187-0127-9074", index: 0, input: "187-0127-9074"]

match

// match 在字符串中查找是否匹配,返回一个数组。找不到则返回null。
console.log(('187-0127-9074187-0127-9074').match(reg)) // null
console.log(('187-0127-9074').match(reg))  // ["187-0127-9074", "187-0127-9074", index: 0, input: "187-0127-9074"]

exec和match的区别

// g 全局模式
var regG = /m/g
console.log(('my name is Test').match(regG))  // ["m", "m"]
console.log(regG.exec('my name is Test')) // ["m", index: 0, input: "my name is Test"]
正则表达式的特殊变量
//使用特殊字符
  /**
   * ^ 匹配输入的开始
   * \ 将特殊字符转义为普通字符
   * @type {RegExp}
   */
  var reg1 = /^123/g
  console.log(reg1.exec('123456'))  // ["123", index: 0, input: "123456"]
  var reg1_1 = /\^123/g
  console.log(reg1_1.exec('123456'))  // null
  console.log(reg1_1.exec('^123456 ^1234 ^1235'))  // ["^123", index: 0, input: "^123456"]

  // $ 匹配输入的结束
  var reg2 = /fan$/
  console.log(reg2.exec('test fan'))  // ["fan", index: 5, input: "test fan"]
  console.log(reg2.exec('test fanc'))  // null

  // * 匹配前一个表达式0次或者多次,等价于{0,}
  var reg3 = /re*/
  console.log(reg3.exec('great')) // ["re", index: 1, input: "great"]
  console.log(reg3.exec('grceat'))  // ["r", index: 1, input: "grceat"]

  // + 匹配前一个表达式1次或者多次,等价于 {1,}
  var reg4 = /l+/
  console.log(reg4.exec('I like lol')) // ["l", index: 2, input: "I like lol"]

  // ? 匹配前一个表达式0次或者1次。等价于 {0,1}
  var reg5 = /a?b/
  console.log(reg5.exec('abcd'))  // ["a", index: 0, input: "abcd"]
  console.log(reg5.exec('bcd')) // ["b", index: 0, input: "bcd"]

  // . 匹配除换行符之后的任何单个字符
  var reg6 = /.e/
  console.log(reg6.exec('e')) //  null
  console.log(reg6.exec('love'))  // ["ve", index: 2, input: "love"]

  // (x) 匹配x并记住匹配项,括号被称为 捕获括号
  var reg7 = /(a)(b)+/
  console.log(reg7.exec('a')) // null
  console.log(reg7.exec('abc')) // ["ab", "a", "b", index: 0, input: "abc"]

  // (?:x) 匹配 'x' 但是不记住匹配项。
  var reg8 = /(?:name){1,2}/
  console.log(reg8.exec('name123'))   // ["name", index: 0, input: "name123"]

  // x(?=y) 匹配'x'仅仅当'x'后面跟着'y'.这种叫做正向肯定查找。
  var reg9 = /name(?=tiptoe)/
  console.log(reg9.exec('nametiptoe123')) // ["name", index: 0, input: "nametiptoe123"]
  console.log(reg9.exec('namet123'))  // null

  // x(?!y) 匹配'x'仅仅当'x'后面不跟着'y',这个叫做正向否定查找。
  var reg10 = /name(?!tiptoe)/
  console.log(reg10.exec('nametiptoe')) // null
  console.log(reg10.exec('namet123')) // ["name", index: 0, input: "namet123"]

  // x|y 匹配x或者y
  var reg11 = /yes|no/
  console.log(reg11.exec('yeno')) // ["no", index: 2, input: "yeno"]
  console.log(reg11.exec('yesn')) // ["yes", index: 0, input: "yesn"]

  // {n} 匹配了前面一个字符刚好发生了n次。
  var reg12 = /1{2}/
  console.log(reg12.exec(1))  // null
  console.log(reg12.exec(11)) // ["11", index: 0, input: "11"]

  // {n,m} 匹配前面的字符至少n次,最多m次。
  var reg13 = /1{1,5}/
  console.log(reg13.exec(123456)) // ["1", index: 0, input: "123456"]
  console.log(reg13.exec(111111111123456))  // ["11111", index: 0, input: "111111111123456"]

  // [xyz] 一个字符集合。匹配方括号的中任意字符,包括转义序列。 你可以使用破折号(-)来指定一个字符范围。
  var reg14 = /[a-z]/
  console.log(reg14.exec('abc123def'))  // ["a", index: 0, input: "abc123def"]
  console.log(reg14.exec('123'))  // null

  // [^xyz] 反向字符集合
  var reg14 = /[^a-z]/
  console.log(reg14.exec('abc123def'))  // ["1", index: 3, input: "abc123def"]
  console.log(reg14.exec('123'))  // ["1", index: 0, input: "123"]

  // /d 匹配一个数字 等价于[0-9]
  var reg15 = /\d/
  console.log(reg15.exec('0123zzz'))  // ["0", index: 0, input: "0123zzz"]
  console.log(reg15.exec('zzz'))  // null

  // /D 匹配一个非数字 等价于[0-9]
  var reg16 = /\D/
  console.log(reg16.exec('0123zzz'))  // ["z", index: 4, input: "0123zzz"]
  console.log(reg16.exec('zzz'))  // ["z", index: 0, input: "zzz"]

  // \w 匹配一个单字字符(字母、数字或者下划线)。 等价于[A-Za-z0-9_]。
  var reg17 = /\w/
  console.log(reg17.exec('@#')) // null
  console.log(reg17.exec('_123')) // ["_", index: 0, input: "_123"]

  // \W 匹配一个非单字字符。 等价于[^A-Za-z0-9_]。
  var reg18 = /\W/
  console.log(reg18.exec('@#')) // ["@", index: 0, input: "@#"]
  console.log(reg18.exec('_123')) // null

引用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,290评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,399评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,021评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,034评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,412评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,651评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,902评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,605评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,339评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,586评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,076评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,400评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,060评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,851评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,685评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,595评论 2 270

推荐阅读更多精彩内容

  • 前言 作为一个程序员,要出去装逼,手中必备的技能就是正则表达式。程序员的正则表达式,医生的处方和道士的鬼画符,都是...
    Layzimo阅读 513评论 0 6
  • 初衷:看了很多视频、文章,最后却通通忘记了,别人的知识依旧是别人的,自己却什么都没获得。此系列文章旨在加深自己的印...
    DCbryant阅读 3,896评论 0 20
  • 9.19--9.23 第7章 正则表达式 正则表达式是一个拆分字符串并查询相关信息的过程。 推荐练习网站: js ...
    如201608阅读 955评论 0 4
  • 锐智喜登科 贺锐智丁酉登科 锐智学堂,师长俊秀,群英汇集,六载精心栽培,育得桃李满园。 锐智学子,...
    昵称怎么可以这么美阅读 205评论 0 1
  • 这哪里是给孩子们写的故事,那些鲜活的人物,美丽的场景,曲折的情节,动人的故事.....那个可爱的孩子桑桑,纯...
    行云流水sxbj阅读 636评论 0 0