美文网首页
第23章 正则表达式作业课堂笔记

第23章 正则表达式作业课堂笔记

作者: kzc爱吃梨 | 来源:发表于2019-10-31 11:40 被阅读0次

\b单词边界

var str = 'hello1 whello9orld hellow2 12-hello8-3456 \t \r jirengu \nruoyu hello3 '

str.match(/\bhello\d\b/)
["hello1, hello2, hello8, hello3"]
//可以看出单词边界是,单词开头或结尾,两边有空格,或者-单词-

稍微改装一下

var str = 'hello1 hello9orld hellow2 12-hello8-3456 \t \r jirengu \nruoyu hello3 '

str.match(/\bhello\d/)
["hello1, hello2, hello9, hello8, hello3"]
//hello9匹配上了,可以看出它前面时单词边界

 var str = 'header3 header clearfix active header-fix'

str.match(/\bheader\d/)
["header", "header"]
//单词边界匹配到了header和header-fix,但是header-fix显然不是我们想要的。
str.match(/(^|\s)header($|\s)/)
["header"]
//使用或来匹配

匹配一个合理的URL

var str = 'http://jirengu.com'
var str2 = 'https://jirengu.com'
var str3 = 'httpssssssssss://jirengu.com'
var str4 = '//jirengu.com'

str.match(/https?:/\/\.+/g)
["http://jirengu.com"]
str2.match(/https?:/\/\.+/g)
["https://jirengu.com"]
str3.match(/https?:/\/\.+/g)
null
str3.match(/https+:/\/\.+/g)
["httpssssssssss://jirengu.com"]

匹配一个合理的URL:
str.match(/^(https?:)?/\/\.+/)
str4.match(/^(https?:)?/\/\.+/)
["//jirengu.com"]

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

reg1.match(/hello|world/g)
["hello"]
reg1.match(/hell(o|s)world/g)
["helloworld"]
reg1.match(/hello)|(world)/g)
["hello", "world"]

空白字符打散

var str = 'h e ll    w ji  ren   gu'
str.split(' ')
["h", "e", "ll", "", "", "", "w", "ji", "", "ren", "", "", "gu"]
str.split('\s')
["h", "e", "l", "l", "w", "j", "i", "r", "e", "n", "g", "u"]

相关文章

网友评论

      本文标题:第23章 正则表达式作业课堂笔记

      本文链接:https://www.haomeiwen.com/subject/nwnenqtx.html