Regular expressions – Basic Practice

Time:2021-1-17

Regular expressions – Basic Practice


After the theoretical basis, we should have some understanding of regular expressions. For example, how to create a regular expression and its matching rules. Then let’s start the actual combat of regular expressions!
It is suggested that you type all the examples in the console window. Only a part of the examples are shown in the examplesSF addressOriginal siteBetter effect!

Evolution of mobile phone number matching

The example code relies on:RegExpObj.test(String)To test whether the regular expression matches the specified string. Successful match returntrue

Phase 1 – character direct quantity: match itself

Suppose a mobile phone number is 13762571094

  • Initial form

/13762571094/.test("13783281094");//false
/13762571094/.test("13762571094");//true

/13762571094/.test("ui13762571094dd");//true
//When a regular expression matches, it returns true as long as the matching content is output, regardless of the previous UI and the following DD
//Finally, this situation is obviously not what we want. Let's go to the next stage of practice

Stage 2 – anchor point: specify matching position

  • ^Match start position

/^http:/.test("http://www.163.com");//true
/^http:/.test("ahttp://www.163.com");//false
/^http:/.test("https://www.163.com");//false
  • $Match end position


/.jpg$/.test("1.jpg");//true
/.jpg$/.test("1.jpg png");//false
/.jpg$/.test("1.png");//false
/.jpg$/.test("regexp.png");//false
  • \b: match word boundaries

/\bis\b/.test("this");//false
/\bis\b/.test("that is reg");//true
  • After understanding the anchor, we have the regularizationFirst evolution

/^13762571094$/.test("13762571094");//true

/^13762571094$/.test("ui13762571094dd");//false
//At this point, this program can correctly recognize the beginning and end of the character. Let's take a look
/^13762571094$/.test("13712345674");//false
/*After trying several numbers, we found that the regular can only recognize the standard mobile phone number
This is obviously not what we want, not the format of identifying a mobile phone number
In the next stage, we will achieve a mobile phone number matching*/

Phase 3 – character class: match one of a class of characters

  • [abc]: A or B or C.[0-9]: a number

  • [^0-9]: a character that is not a number.[a-z]: one letter

  • .: any character (except newline)

[0-9]/.test("123")//true
/[0-9]/.test("asd")//false
/[^0-9]/.test("asd")//true
/[a-z]/.test("asd")//true
/./.test("allen")//true
/./.test("12")//true
  • After understanding the character class, we can do the followingSecond evolution (50%. Now you can match a mobile phone number!

/^1[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$/.test("13762571094");//true
/^1[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$/.test("13712345678");//true
//Does it feel that the code is too long? [0-9] is full of five characters. In order to save effort, of course, it won't be done like this. Continue to look down
Metacharacter – a character with a special meaning

In fact, we have used it before

  • ^$\b

  • \d:[0-9]\D:[^\d]

  • \s: white space.\S:[^\s]

  • \w:[A-Za-z0-9_]\W:[^\w]

/\d/.test("123");//true
/\d/.test("1dsf");//true
/\D/.test("1dsf");//true
/\D/.test("123");//false
//Let's experiment with some more examples
  • After understanding the metacharacter, we can do itSecond evolution (100%)It’s too late.

/^1\d\d\d\d\d\d\d\d\d\d$/.test("13762571094");//true
/^1\d\d\d\d\d\d\d\d\d\d$/.test("13712345678");//true
/^1\d\d\d\d\d\d\d\d\d\d$/.test("1376257109x");//false
//Does it feel that the code is much shorter than just now? But it's not enough. Nothing can stop me from being lazy. Let's continue to learn

Stage 4 – quantifiers: the number of occurrences

  • {n,m}: n to m times.?{0,1}

  • +:{1,}*:{0,}

/\d*/.test("abc");//true
/\d+/.test("abc");//false
/\d+/.test("1abc");//true
/^https?:/.test("http://www.163.com");//true
/^https?:/.test("https://www.163.com");//true
/^https?:/.test("httpss://www.163.com");//false
  • At this point, our regular expression to match the mobile phone number is herefinal phaseIt’s over

/^1\d{10}$/.test("13762571094");//true
/^1\d{10}$/.test("13712345678");//true
/^1\d{10}$/.test("1376257109x");//false
//Here, the mobile phone number is matched!

Note – escape character: the character to be matched is metacharacter

/^http:/\/\/../@163\.com$/

/http:\/\//.test("http://www.163.com");//true
/@163.com$/.test("[email protected]");//true
/@163.com$/.test("[email protected]");//true
/@163\.com$/.test("[email protected]");//true
/@163\.com$/.test("[email protected]");//false

Multiple branches: Netease mailbox matching

/thi(c|n)k/===thi[cn]k
\.(png|jpg|jpeg|gif)$: check whether a file is a picture file

/(\ W +) @ (163 | 126 | 188) \. Com $/. Test ("Guo, Christmas @ 163acom") // false
/(\w+)@(163|126|188)\.com$/.test("[email protected]")//false
/(\w+)@(163|126|188)\.com$/.test("[email protected]")//true

capture

  • Save the matching string for later use

  • (): capture/(\w+)@(163|126|188)\.com$/

  • (?:): do not capture/(\w+)@(?:163|126|188)\.com$/

  • use:

    • $1,$2,…

    • API parameters or return values

Get the matching string:String.match(regexp)

var url = 'http://blog.163.com/album?id=1#comment';
var reg = /^(https?:)\/\/([^\/]+)(\/[^\?]*)?(\?[^#]*)?(#.*)?$/;
//Var reg = / ^ (HTTPS?:) \ / \ / ([^ \ /] +) ([^ \?] * ([^ #] *) (. *) $// / is the same as above;

var arr = url.match(reg);

//Arr [0] is the original string“ http://blog.163.com/album?id=1#comment "
//The character matched by the corresponding bracket
var protocol= arr[1]//"http:"
var host= arr[2]//"blog.163.com"
var pathname= arr[3]//"/album"
var search= arr[4]//"?id=1"
var hash= arr[5]//"#comment"

Replace a substring:str.replace(regexp/substr,replacement)

  • When the second parameter is a character

var str = "the price of tomato is 5, the price of apple is 10."
str.replace(/(\d+)/,"$1.00")
"the price of tomato is 5.00, the price of apple is 10."
//Use global mode
str.replace(/(\d+)/g,"$1.00")
"the price of tomato is 5.00, the price of apple is 10.00."
  • When the second parameter is a function

Var HTML = '< label > website: < / label > < input placeholder = "start with http: //" >';
html = html.replace(/[<>]/g, function(m0){
    switch(m0){
        case '<':
            return '&lt;';
        case '>':
            return '&gt;';
    }
});
console.log (HTML); // & lt; label & gt; website: & lt; & label & gt; & lt; input placeholder = "start with http: //" & gt;

More powerful retrieval-regexpObj.exec(str)

  • More detailed results: index

  • The state of the process: lastindex

I don’t think I can use it. I don’t want to talk about it. If you like it, please recommend it^_^

Recommended Today

DK7 switch’s support for string

Before JDK7, switch can only support byte, short, char, int or their corresponding encapsulation classes and enum types. After JDK7, switch supports string type. In the switch statement, the value of the expression cannot be null, otherwise NullPointerException will be thrown at runtime. Null cannot be used in the case clause, otherwise compilation errors will […]