Note: Re is used on strings. In javascript weak languages, when you use numbers, be careful to convert them to strings as well

1. The way to define the re

  • 1. Simple and direct definition (often used)

    var reg = /javascript/gi
    Copy the code
  • 2. Create a regex using object mode (using this mode creates a variable to match)

    var reg = new RegExp('javascript', gi)
    Copy the code

Two, metacharacters understanding

  • 1. Metacharacters of special significance
    • \: Indicates the meaning of the escaped character
    • ^: starts with a metacharacter
    • $: Ends with a metacharacter
    • \n: matches a newline character
    • .: Any character except \n
    • \o: NUL character (\u0000)
    • \t: TAB (\u0009)
    • \v: Vertical TAB (\u000B)
    • \f: Page feed (\u000C)
    • \r: Carriage return character (\u000D)
  • 2. Quantifier metacharacters representing the number of occurrences
    • *: Appears 0 to multiple times
    • +: Appears 1 to multiple times
    • ?: Zero or one (or uncapture greed)
    • {n}: appears n times
    • {n,m}: occurs n to m times

Three, the understanding of modifiers

  • x|y: either x or Y
  • [xyz]: either x, y or Z
  • [^xyz]: Any character except xyz
  • [a-z]: Any character between a and Z
  • [^a-z]: any character except a and z
  • \d: A number ranging from 0 to 9
  • \D: Any character except a number ranging from 0 to 9
  • \b: a boundary character
  • \w: Any character can be digits, letters, or underscores
  • \s: matches a whitespace character or space
  • (a)Grouping, the division of a large regular itself into smaller regular forms, for example:var reg = /^(\d+)zhufeng(\d+)$/;

Four, several modifiers

  • 1.gRepresents global match
  • 2,iIgnore case
  • 3,mIndicates that multiple rows can be matched

Five,[]The use of

  • 1. All characters in brackets are their own meanings (no special meanings).

    var reg = / [.] / // Match to.
    var reg = / /. /  // Match to.
    Copy the code
  • 2. Indicates any character

    var reg = /[xyz]/ // match x or y or Z
    var reg = /[a-zA-Z]/ // represents either a-z or a- Z
    Copy the code
  • Brackets do not recognize two-digit numbers

    var reg = $/ / ^ [12]; // --> 1 or 2 (fit [xyz])
    var reg = $/ / ^ [12-68]; // --> 1; // --> 1
    var reg = /^[\d]+$/; // To match one or more numbers
    Copy the code
  • 4, take the reverse operation

    var reg = /[^abc]/; // Represents characters other than ABC
    Copy the code

Vi.(a)(changes the priority of operations like mathematics)

  • 1. Use of groups

    var reg = 18 | $19 / / ^; // 18, 19, 181, 189, 119, 819, 1819
    var reg = $/ / ^ 18 | (19); // Only 18 or 19
    Copy the code

Seven,Several important methods in regularization

  • 1. The test method tests whether a given string matches a condition, returning true or false

    var reg = /[x|y]/
    reg.test('|')
    Copy the code
  • 2. Match retrieves all the characters that match the regex.

    var str = 'hello JAVA and javascript';
    str.match(/java/gi); Return ["JAVA", "JAVA"]
    Copy the code
  • 3. Exec match (step by step)

    The first element is the matched element, the second element is the position of the matched element in the string, the third element is the entire string, and null is returned if there is no match

    var str = 'hello JAVA and javascript';
    var reg = /java/gi;
    reg.exec(str); // return ["JAVA", index: 6, input: "hello JAVA and javascript"]
    reg.exec(str); // return [" Java ", index: 15, input: "hello Java and javascript"]
    reg.exec(str); / / returns null
    Copy the code
  • 4, split split (maybe you can say that the string itself has split merge with regular split)

    'a b c'.split(' '); // return ["a", "b", "", "", "c"]
    'a,b, c d'.split(/[\s\,]+/); Return ["a", "b", "c", "d"]** The following is used in my project, with text highlighting **var str = 'helloJAVAandjavascript';
    str.split(/(java)/gi); / / return [" hello ", "JAVA", "and", "JAVA" and "script"], and then re-use label stitching
    Copy the code
  • Replace, which provides the same method in strings

    • Use string substitutions

      var str = 'iceman2016iceman2017';
      str.replace('iceman'.'shoushou');
      Copy the code
    • Use regular substitutions

      var str = 'iceman2016iceman2017';
      str.replace(/iceman/g.'shoushou');
      Copy the code
    • The second argument can also be a function

      var str = 'iceman2016iceman2017';
      str.replace(/iceman/g.function () {
          // The first argument is matched by the re,
          // The second argument is the index of the character matched to the group if there is a group, and the index of the character matched to the group if there is no group
          // The third argument is the original character
          ["iceman", 0, "iceman2016iceman2017"]
          ["iceman", 10, "iceman2016iceman2017"]
          console.log(arguments);
          return 'shoushou';
      });
      Copy the code
    • An explanation of the second argument to replace

      var str = 'he12llo wo21rd';
      str.replace(/o/g.function (all, letter,) {
        console.log(all)
        console.log('= = = =',letter) // return 6,9
      });
      Copy the code
      var str = 'he12llo wo21rd';
      str.replace(/(o)/g.function (all, letter,) {
        console.log(all)
        console.log('= = = =',letter) // Return o, o
      });
      Copy the code
    • Use case for Replace (convert to hump name)

      var s1 = 'foo-style-css';
      s1 = s1.replace(/-(\w)/g.function (all, letter) {
        return letter.toUpperCase();
      })
      Copy the code
  • 6, search returns the subscript if the content is matched, otherwise returns -1

    var str = 'hello JAVA and javascript';
    str.search(/java/i);
    Copy the code

Eight, aboutThe $1... $9The understanding of the

  • 1. () means grouping in re

  • $= 0; $= 0; $= 0; 9 indicates the serial number of the group

  • 3, $1… $9 should be used in combination with the () group

  • 4. Use cases

    var s="abcdefghijklmn";
    var reg = /(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)/gi;
    var result = s.replace(reg, '$1, $2, $3, $4, $5 and $6, $7 to $8 and $9 and $10 and $11 to $12 to $13, $14');
    / / return the result: 'a, b, c, d, e, f, g, h, I, j, k, l, m, n'
    Copy the code
  • 5. Change the hump to a hyphen

    export const splitStr = (str) = > str ? str.replace(/([A-Z])/g."$1").toLowerCase() : ' ';
    Copy the code

Ix. Some cases

  • 1. Match the ID number

    var reg = /^(\d{2})(\d{4})(\d{4})(\d{2})(\d{2})(? :\d{2})(\d)(? :\d|X)$/;
    var str = "350324202904190216";
    str.match(reg)
    Copy the code
  • 2. Convert numbers to uppercase numbers

    var ary = ['zero'.'one'.'. '.'叁'.'boss'.'wu'.'land'.'pure'.'捌'.'nine'.'pick up'];
    '200801'.replace(/\d/g, (args1, args2, args3) => {
        // The first argument is the number of matches, the second argument is the index of matches, and the third argument is the entire string
    	console.log(args1, args2, args3)
    	return ary[args1]
    })
    Copy the code
  • 3. Capitalize the first letter

    var str = 'hello word';
    str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
    Copy the code
  • 4. Matches null characters

    var reg = $/ / ^
    reg.test(' '); / / return true
    Copy the code
  • 5, match a character or space to start

    var reg = /(^|\\s)(|\\s$)/;
    Copy the code
  • 6. The thousandth of the currency

    const currency = (str) = > str.toString().replace(/\B(? =(\d{3})+(? ! \d))/g.",");
    Copy the code

10. Extension points

  • 1. Special characters need to be entered in the text box

    '*'.replace(/[-\/\\^$*+?.()|[\]{}]/g.'\ \ $&')
    // Output :"\.\*"
    Copy the code