Introduction to javascript regular expressions basics

  • 2020-06-01 08:10:44
  • OfStack

What are the benefits of regular expressions? Let's take a look at them:
We use the string processing method in js to write a function to extract the number in the string:


 var str='dgh6a567sdo23ujaloo932';
   function getNumber(obj){
     var arr=[];
     for (var i = 0; i < obj.length; i++) {
       if (obj.charAt(i)>='0'&&obj.charAt(i)<='9'){
           arr.push(obj.charAt(i));
         }
     }
     return arr;
   };
   console.log(getNumber(str));  //["6", "5", "6", "7", "2", "3", "9", "3", "2"]

In the above method, we took the number in the string, but we were not satisfied. What we needed was the form of ['6','567','23','932'], and modified the function:


function getNumber(obj){
    var arr=[];
    var temp='';
    for (var i = 0; i < obj.length; i++) {
      if (obj.charAt(i)>='0'&&obj.charAt(i)<='9'){
          temp+=obj.charAt(i);// Now join the adjacent Numbers 
        }
        else{ // Whenever the number of the connection is disconnected, it is executed here 
          if (temp) {
            arr.push(temp);
            temp='';
          }
        };
    }
    if (temp) { // The purpose here is to show the final number, for reasons I don't want to explain 
            arr.push(temp);
            temp='';
          }
    return arr;
  };

So let's use regular expressions to solve the functions of this function:


function getNumber2(obj){
    var arr=[];
    var re=/\d+/g;
    arr.push(obj.match(re));
    return arr;
  };

Take a full look at the results:


<!DOCTYPE>
<html>
<head>
  <meta charset='utf-8'>
  <title></title>
</head>
<script type="text/javascript">
window.onload=function(){
  var str='dgh6a567sdo23ujaloo932';
  /*function getNumber(obj){
    var arr=[];
    for (var i = 0; i < obj.length; i++) {
      if (obj.charAt(i)>='0'&&obj.charAt(i)<='9'){
          arr.push(obj.charAt(i));
        }
    }
    return arr;
  };*/
  function getNumber(obj){
    var arr=[];
    var temp='';
    for (var i = 0; i < obj.length; i++) {
      if (obj.charAt(i)>='0'&&obj.charAt(i)<='9'){
          temp+=obj.charAt(i);// Now join the adjacent Numbers 
        }
        else{ // Whenever the number of the connection is disconnected, it is executed here 
          if (temp) {
            arr.push(temp);
            temp='';
          }
        };
    }
    if (temp) { // The purpose here is to show the final number, for reasons I don't want to explain 
            arr.push(temp);
            temp='';
          }
    return arr;
  };
  function getNumber2(obj){
    var arr=[];
    var re=/\d+/g;
    arr.push(obj.match(re));
    return arr;
  };
  console.log(getNumber(str));
  console.log(getNumber2(str)); 
};
</script>
<body>
</body>
</html>

As you can see from the above example, the regular expression method has the same effect, but the code is shorter and more efficient, which is the benefit of regularization
Regex is created for more efficient string processing, just like string processing method 1, but more efficient and concise (regex can only deal with strings).

Now let's systematically learn 1, a few common regular methods:

Before I do that, I'm going to write the regular. Regular and other objects, array (), object (), Date (), all have a way to initialize
var re=/ where you have to write something that matches, if you don't, you're looking at the sign /; // this is the simple creation of the regular object, which I will use directly in the following articles
var re = new RegExp (); // this creation method is also ok, you know, except that the parameter passing is a little different from the shorthand

(1) test

Meaning: to match the string regularly, true is returned when the match is successful, false is returned otherwise;
Syntax: re. test(string);
Let's start with the escape characters:
/s Spaces /S non-spaces /d Numbers /D non-numbers /w characters (alphanumeric, underlined) /W non-characters
For example, determine whether a string is a number


<!DOCTYPE>
<html>
<head>
  <meta charset='utf-8'> 
  <title></title>
</head>
<script type="text/javascript">
window.onload=function(){
  var str='dgh6a567sdo23ujaloo932';
  var str2='123456';
  function allNumber(obj){
    var re=/\D/;// Define a regular object that matches a non-number and returns the result whenever there is a non-number 
    if (re.test(obj)) {
      alert(' It's not all Numbers ');
    }
    else{
      alert(' All digital ');
    };
  };
  allNumber(str);
  allNumber(str2);

};
</script>
<body>
</body>
</html>

(2) search

Meaning: regular to match the string, when the match is successful to return the successful matching position, otherwise, return -1; indexof () and string handling methods
Syntax: string.search(re);
[color=Red] note: regular is case-sensitive by default. To make it case-insensitive, you need to identify i; [/ color]
Example, case - insensitive to the regular matching of a character in a string


<!DOCTYPE>
<html>
<head>
  <meta charset='utf-8'> 
  <title></title>
</head>
<script type="text/javascript">
window.onload=function(){
  var str='dgh6b567sdo23ujaloo932';
  function searchStr(obj){
    var re=/B/i;// Define a regular object match b Character, case - insensitive 
    alert(obj.search(re));  
  };
  searchStr(str);
};
</script>
<body>
</body>
</html>

(3) the match

Meaning: to match a string in a regular way, return the matched array when the match is successful, or Null if it is not
Syntax: string.match(re);
[color=Red] note: the default in the regex is to return the corresponding value as soon as the match is successful, and the match will not continue. If you want to find all of them, you need to add g (global matching) [/color]
Example: match consecutive Numbers in a string and store them in an array (consecutive Numbers are used as an item in an array)

The "+" in the program is matched at least once. Why do you want to do that?
As mentioned earlier, "the default in the regular rule is to return the corresponding value as soon as the match is successful", so the match to 1 number in the string will be finished, and 1 number will be returned to the array. In this case, we need to use g to make it match each element.
Have you found that there is no definite number of consecutive Numbers, and the number of dynamic Numbers can be satisfied by "+"?


<!DOCTYPE>
<html>
<head>
  <meta charset='utf-8'> 
  <title></title>
</head>
<script type="text/javascript">
window.onload=function(){
  var str='dgh6b567sdo23ujaloo932';
  function searchStr1(obj){
    var re=/\d/;  
    return obj.match(re);
  };
  function searchStr2(obj){
    var re=/\d/g;  
    return obj.match(re);
  };
  function searchStr3(obj){
    var re=/\d\d/g;// The global matching 2 digits   
    return obj.match(re);
  };
  function searchStr4(obj){
    var re=/\d+/g;  
    return obj.match(re);
  };
  console.log(searchStr1(str));
  console.log(searchStr2(str));
  console.log(searchStr3(str));
  console.log(searchStr4(str));

};
</script>
<body>
</body>
</html>

(4) replace

Meaning: to match a string in a regular way, when the string that matches is replaced by a new string
Syntax: string.replace(re);
Example: replace all a in the string with b


<!DOCTYPE>
<html>
<head>
 <meta charset='utf-8'> 
 <title></title>
</head>
<script type="text/javascript">
window.onload=function(){
 var str='daah6b5a7sdo23ujaloo932';
 function replaceStr(obj){
  var re=/a/g; // The global matching a
  return obj.replace(re,'b');
 };
 console.log(replaceStr(str));
};
</script>
<body>
</body>
</html>

Write here for the moment to follow up with the new...

That's all for this article, I hope you enjoy it.


Related articles: