Regular expressions – Basic Practice


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


//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

  • $Match end position

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

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


//At this point, this program can correctly recognize the beginning and end of the character. Let's take a look
/*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)

  • After understanding the character class, we can do the followingSecond evolution (50%. Now you can match a mobile phone number!

//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]

//Let's experiment with some more examples
  • After understanding the metacharacter, we can do itSecond evolution (100%)It’s too late.

//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,}

  • At this point, our regular expression to match the mobile phone number is herefinal phaseIt’s over

//Here, the mobile phone number is matched!

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


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

Multiple branches: Netease mailbox matching

\.(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


  • 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 = '';
var reg = /^(https?:)\/\/([^\/]+)(\/[^\?]*)?(\?[^#]*)?(#.*)?$/;
//Var reg = / ^ (HTTPS?:) \ / \ / ([^ \ /] +) ([^ \?] * ([^ #] *) (. *) $// / is the same as above;

var arr = url.match(reg);

//Arr [0] is the original string“ "
//The character matched by the corresponding bracket
var protocol= arr[1]//"http:"
var host= arr[2]//""
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."
"the price of tomato is 5.00, the price of apple is 10."
//Use global mode
"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){
        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 […]