Introduction and syntax of regular expressions

Regular expression

  • Regular expressions are used to define some string rules
  • The computer can check whether a string conforms to the rule according to the regular expression, or extract the content that conforms to the rule in the string
  • Syntax:
    var variable = new RegExp("regular expression", "matching pattern")

var reg = new RegExp("a","i" ); //i ignore case
console.log(typeof reg); //Object
console.log(reg);

  • Use typeof to check regular objects will return object

  • var reg = new RegExp("a");
    This regular expression can check whether a string contains a

  • Regular expression method
    test()

  • Using this method can be used to check whether a string contains regular expression rules, if it meets the rules, it will return true, otherwise it will return false

var reg = new RegExp(“a”,“i” );
var str = “abc”;
var result = reg.test(str); //返回true
console.log(result);

  • In the constructor, you can pass a matching mode as the second parameter, which
    can be i (ignoring case)
    g (global matching mode)

var reg = new RegExp("a","i" ); //i ignore case

  • Use literals to create regular expressions
  • Syntax:
    var variable = /regular expression/matching pattern
    var reg = /a/i;
  • The way to use literals is simpler, and it is more flexible to use constructors to create

var reg = /a/i;
console.log(reg);
console.log(typeof reg);

  • Use | to indicate or

//Create a regular expression and check whether a string contains a or b
var reg = /a|b/;
console.log(reg.test("bcd"));

  • The content in [] is also an OR relationship
    [ab] == a|b
    [az] Any lowercase letter
    [AZ] Any uppercase letter
    [Az] Any letter
    [^] Except
    [0-9] Any number

var reg = /[abcdefg]/i;
console.log(reg.test(“D”));

//Check whether a string contains abc or adc or aec
var reg =/a[bde]c/;
console.log(reg.test("adc"));

var reg = /[^ab]/; //All return true except for ab
console.log(reg.test("abc"));

Guess you like

Origin blog.csdn.net/weixin_48769418/article/details/111564243