• Uncategorized
  • 0

[JavaScript] An article to understand the regular expression of JS

Hits: 0

🍈 About the author: Hello everyone, I’m Yi Shifanhua, a college student who is eager to reserve his knowledge

🍇 Personal homepage: Yi Shifanhua [,’s blog]

🍓 Series column: JavaScript column

Table of contents

🏍️ Regular Expressions

🍇 Create regular expressions

constructor creation

literal creation

🍈 Regular grammar

or | and [ ]

matches letters [letters-letters]

remove unique [^content]

🍉 String object methods for regular expressions

search()

match()

replace()

split()

🍊 Regular Expression Syntax

quantifier

Regular phone number

mail regex

translate characters

metacharacter

🏍️ [Regular Expressions]

Regular expressions are used to define the rules of some strings. The computer can check whether a string conforms to the rules according to the regular expressions, and extract the content that conforms to the rules in the string .

🍇 Create regular expressions

constructor creation

Syntax: var variable = new RegExp(“regular expression”, “match pattern”);

The test() method can be used to check whether a string matches the rules of a regular expression, and returns true if it matches, false otherwise.

< script > // This regex checks if our string contains a var reg = new RegExp ( "a" );
     var str = "a" ;
     var result = reg.test(str)
     console .log(result) ;
     console .log(reg.test( "a" ));
     console .log(reg.test( "ddagsgts" ));
     console .log(reg.test( "dAAAgsgts" ));
     console .log(reg.test ( "dgsgts" ));
 </ script >

A matching pattern can be passed as the second parameter in the constructor. For example: i ignore case g global match pattern

< script > // This regex checks if our string contains abc var reg = new RegExp ( "abc" , "i" );
     var str = "abc" ;
     var result = reg.test(str)
     console . log(result);
     console .log(reg.test( "abc" ));
     console .log(reg.test( "AbC" ));
     console .log(reg.test( "AC" ));
 </ script >

literal creation

Syntax: var variable = /regex/match pattern

< script > // This regular expression can check if our string contains abc // var reg = new RegExp("abc","i"); // The same effect as the regular expression created by the constructor above, the two The difference between the two: the creation of literals is easy, and the construction is flexible 
    reg = /abc/i ;
     console .log(reg.test( "abc" ));
     console .log(reg.test( "AbC" ));
     console .log( reg.test( "AC" ));
 </ script >

🍈 Regular grammar

or | and [ ]

< script > // Create a regular expression to check two or more of them, such as checking whether there is a or b. // Use | to mean "or", the content of [] also means or, [ab] == a | b; 
    reg = /a | b/i ;


    reg = /[ab]/i;
    console.log(reg.test("abc"));
    console.log(reg.test("AbC"));
    console.log(reg.test("C"));
</script>

matches letters [letters-letters]

According to the above I want to get any letter and return true, how should I do it? Please see:

< script > // [az] any lowercase letter // [AZ] any uppercase letter // [Az] any letter 
    reg = /[Az]/ ;
     console .log(reg.test( 'BUDfvd' )); // true </ script >

According to the above content, I want to check whether the string contains abc or afc or agc. How can I match it in an easy way? as follows:

< script > // According to the observation, the regular matching starts with a and ends with c. The matching is as follows: 
    reg = /a[bfg]c/ ;
     console .log(reg.test( "afc" )) ; //true console .log(reg.test( "agc" )); //true console .log(reg.test( "adc" )); //false </ script >

remove unique [^ content]

< script > // remove only content[^content] 
    reg = /[^ab]/ ;
     console .log(reg.test( "ab" )); //false console .log(reg.test( "agc" )); //true console .log(reg.test( "abc" )); //true </ script >

Now I want to remove the content that only has numbers

< script > // remove only numbers [^content] 
    reg = /[^0-9]/ ;
     console .log(reg.test( "14151" )); //false console .log(reg.test( "agc" )); //true console .log(reg.test( "31313abc4141" )); //true </ script >

🍉 String object methods for regular expressions

method describe
search Retrieve values ​​that match a regular expression
match Find a match for one or more regular expressions
replace Replace substrings that match a regular expression
split split string into string array

search()

You can search whether the string contains the specified content. If the specified content is searched, it will return the index of the first occurrence. If it is not searched, it will return -1. It can receive a regular expression as a parameter, and then it will be based on the regular expression. to retrieve the string.

< script > var str = 'hello abc world aec hello afc people' ;
     // search if string contains abc aec afc var result = str.search( /a[bef]c/ );
     var result1 = str.search( /a[k]c/ )
     console .log(result);
     console .log(result1);
 </ script >

match()

The matching content can be extracted from a string according to a regular expression. By default, our match will only find the first content that meets the requirements, and stop retrieving after it is found. We can set the regular expression as the global matching mode, so that all content will be matched.

< script > 
    str = '1a2b3c4d5e6f7A8B9C' ;
     // Multiple matching patterns can be set for a regular expression, and the order does not matter 
    result = str.match( /[az]/ig );
     console .log(result);
     // match () will encapsulate the matched content into an array and return it, even if only one result is found. 
    console .log( Array .isArray(result));
     console .log(result[ 1 ]);
 </ script >

replace()

You can replace the specified content in the string with new content; parameters: 1. The replaced content can accept a regular expression as a parameter; 2. New content; only one will be replaced by default.

< script > 
    str = '1a2b3c4d5e6f7A8B9C' ;
     // replace first 
    result by default = str.replace( /a/ , '$_$' );
     console .log(result);
     // replace global letters 
    result2 = str.replace ( /[az]/gi , '$_$' );
     console .log(result2);
     // replace letters with nothing, only keep numbers 
    result3 = str.replace( /[az]/gi , '' );
     console .log(result3);
 </ script >

split()

A string can be split into an array, and a regular expression can be passed as a parameter to the method to split the string

<script>
    var str = '1a2b3c4d5e6f7g8';
    var result = str.split(/[A-z]/);
    console.log(result);
</script>

🍊 Regular Expression Syntax

quantifier

The number of occurrences of a content can be set through the quantifier, and the quantifier only works on the content before it – {n} occurs exactly n times

<script>
    reg = /a{3}/;
    console.log(reg.test("aaabc"));
    console.log("---------------");
    reg = /ab{3}/;
    console.log(reg.test("ababab"));
    console.log(reg.test("abbbc"));
    console.log("---------------");
    reg = /(ab){3}/;
    console.log(reg.test("ababab"));
</script>

Through the quantifier, we can also set the number of occurrences, {n,m} can be from n to m times, of course, set {1,} to represent more than 1 time.

<script>
    reg = /ab{1,3}c/;
    console.log(reg.test("abc"));
    console.log(reg.test("abbc"));
    console.log(reg.test("abbbc"));
</script>

Quantifier summary
quantifier describe
n+ matches any character containing at least one n
n* matches any character containing zero or more n
n? matches anything containing zero or one n characters
n{X} matches a string containing X sequences of n
n{X,Y} matches a string containing X or Y sequences of n
n{X,} matches a sequence string containing at least X n
n$ matches any string ending with n
^n matches any string starting with n
?=n matches any string immediately followed by the specified string n
?!n matches any string not immediately followed by the specified string n

Examples of quantifiers :

< script > // at least one, equivalent to {1,} 
    reg = /ab+c/ ;
     console .log(reg.test( "ac" ));
     console .log(reg.test( "abc" ));
     console .log(reg.test( "abbc" ));
     console .log( "---------------" );
     // 0 or more, equivalent to {0, } 
    reg = /ab*c/ ;
     console .log(reg.test( "ac" ));
     console .log(reg.test( "abc" ));
     console .log(reg.test( "abbc" )) ;
    console
    .log( "---------------" );
     // 0 or one, equivalent to {0,1} 
    reg = /ab?c/ ;
     console .log(reg. test( "ac" ));
     console .log(reg.test( "abc" ));
     console .log(reg.test( "abbc" ));
     console .log( "--------- ------" );
     // ^ means the beginning, $ means the end 
    // If both ^ and $ are used in the regular expression, the string must exactly conform to the regular expression. Can only be an a 
    // If you want to start with a and end with a: /^a/&&/a$/; 
    reg = /^a/ ;
     console .log(reg.test( "ac" ));
     console . log(reg.test( "));
    console.log("-----------");
    reg = /a$/;
    console.log(reg.test("bfgqga"));
    console.log(reg.test("bfgeaaqg"));
    console.log("----------------");
    reg = /^a$/;
    console.log(reg.test("a"));
    console.log(reg.test("aa"));
    reg = /^a/&&/a$/;
    console.log(reg.test("aa"));
</script>

Regular phone number

Create a regular expression to check if a string is a valid mobile phone number.

Domestic mobile phone number rules :

  1. The first digit starts with 1 ^1

  2. The second digit 3-9 Any number [3-9]

  3. Any number after three digits is 9 [0-9]{9}$

<script>
    var phoneReg = /^1[3-9][0-9]{9}$/;
    var phoneStr = '13252278267';
    var phoneStr1 = '11252278267';
    console.log(phoneReg.test(phoneStr));//true
    console.log(phoneReg.test(phoneStr1));//false
</script>

mail regex

Create a regular expression that checks whether a string is a normal, valid email.

Email rules : (QQ as an example)

  1. The first arbitrary alphanumeric underscore \w{3,}

1.1. The first point may appear in the middle of a dot \w{3,}(.\w+)*

  1. Second place @ @

  2. The third arbitrary alphanumeric [A-z0-9]+

  3. The fourth digit. Any letter (2-5 digits) (there will be multiple) (.[Az]{2,5}){1,2}

< script > // ^ and $ are added to indicate a complete email and cannot be omitted var emailReg =   /^\w{3,}@[A-z0-9]+(\.[Az]{2,5} ){1,2}$/ ;
     var email = '31444144141@qq.com' ;
     console .log(emailReg.test(email));
 </ script >

translate characters

Use \ as a translation character in regular expressions.

< script > // Check whether a character contains . , . means any character, we need to tell the computer through translation that what we are checking is a . ; // \. means. ; \\ means \ var reg = /\./ ;
     var reg1 = /\\/ ;
     console .log(reg.test( "bbb.ff" ));
     console .log(reg1.test( "bbb\\ff" )); //slashes are also in strings The translation character, a slash will translate the following quotes, so we need two slashes </ script >

metacharacter

< script > // \w any letters, numbers, _ [A-z0-9] // \W except letters, numbers, _ [^A-z0-9] 
    reg = /\w/ ;
     console .log(reg .test( '12faf' ));


    reg = /\W/ ;
     console .log(reg.test( "$$$" ));
     console .log( "---------------" );
     // \d Any number [0-9] 
    // \D except numbers [^0-9] 
    reg = /\d/ ;
     console .log(reg.test( '12079' ));
    reg = /\D/ ;
     console .log(reg.test( "$$jbvkj$" ));
     console .log( "---------------" );
     // \ s space 
    // \S except space 
    reg = /\s/ ;
     console .log(reg.test( '1 2079' ));
    reg = /\S/ ;
     console .log(reg.test( " " ));
     console .log( "---------------" );
     // \b word boundary 
    / / \B except word boundaries 
    reg = /\bhello\b/ ; //check if the word is in the string 
    console .log(reg.test( 'hello world' ));
     console .log(reg.test( 'helloworld ' ));
     console .log( "---------------" );
 </ script >

Examples of removing spaces :

< script > // remove spaces and replace spaces with "" var str = " admin " ;
     console .log(str);
     // remove leading spaces // str = str.replace(/^\s*/,"" ); // console.log(str); // remove trailing whitespace // str = str.replace(/\s*$/,"") // console.log(str); // remove leading and trailing whitespace 
    str = str.replace( /^\s* | \s*$/g , "" )
     console .log(str);
 </ script >

🍃The learning of JavaScript still needs more practice. Friends who want to practice JavaScript are recommended to go to Niuke.com to take a look. Link: The IT question bank in [Niuke] . , the most important thing is that the resources inside are free, it is course + brushing questions + face-to-face + job search + discussion area sharing, a one-stop job search learning website, you can go and see if you are interested.

Woohoo~ Originality is not easy.

You may also like...

Leave a Reply

Your email address will not be published.