Learning regular 2


Now let’s practice their usage

//Verification method
function verificationRule(reg,str){
  return reg.test(str)

Examples of boundaries

//Take JavaScript as the left boundary
verificationRule(/\bjavascript/,'javascript') // true

//With script as the right boundary
verificationRule(/script\b/,'javascript') // true 

//^ match at the beginning of the line and $at the end of the line. Starts with an alphanumeric underscore and ends with a
verificationRule(/^\wa$/,'mike_ma') // true

Examples of times

//Match one to more
verificationRule(/\w+/,'hello') // true

//Match 0 to 1
verificationRule(/ed?/,'hello') // true

//Match 0 to more than one
verificationRule(/ed*/,'mike') // true
verificationRule(/ed*/,'word') // true
verificationRule(/ed*/,'javascript') // false

//Match 3 numbers
verificationRule(/\d{3}/,'5654') // true

It is easy to ignore the problem of word boundary, and the regular matching will return true

verificationRule(/ed*/,'vghfgygihedk') // true
verificationRule(/^ed*$/,'vghfgygihedk') // false
verificationRule(/^ed*$/,'ed') // true

An example of or

The metacharacters that represent or are commonly used are two|and []; each metacharacter in brackets indicates that it may exist in the string.

verificationRule(/x|y/,'xffasihdg') // true
verificationRule(/x|y/,'yasdngkia') // true
verificationRule(/x|y/,'awett') // false
verificationRule(/[x,y]/,'yasdngkia') // true
verificationRule(/[x,y]/,'xjaskuifhx') // true
verificationRule(/[x,y]/,'asfdas') // false

An example of a grouping

If we want to match X or Y exactly, we need to use grouping ()

verificationRule(/^(x|y)$/,'x') // true
verificationRule(/^(x|y)$/,'y') // true
verificationRule(/^(x|y)$/,'xy') // false

Examples of ranges

Brackets indicate possible characters. Numbers can also be represented by [0-9] in addition to D. similarly, upper case letters A-Z can be written as [A-Z], and lower case letters can be written as [A-Z]
We can also use brackets to indicate the reverse, such as1Except for ABC

/^[0-9A-Za-z_ ]+$/ is equivalent to / ^ \ w+$/  
 /^[^ s] + $/ is equivalent to / ^ s+$/

Examples of modifiers

There are only three modifiers

//G global match
"this is test".match(/is/g);//["is", "is"]

//M multi line matching
"\nIs th\nis it?".match(/^is/m);//["is"]

//I ignore case
"Hello Word".match(/word/i) // ["word"]

  1. abc ↩

Recommended Today

Deep understanding of HTTP protocol

*Foreword: I’d like to share with you an article about my experience since I developed it, Let’s share a personal understanding of HTTP* -Maojiale😊 What are the methods of HTTP? HTTP 1.0 defines three request methods: get, post and head HTTP1.1 adds five request methods: options, put, delete, trace and connect What are the specific […]