Summary of regular expressions in JavaScript

Note: Regular rules are used on strings. javascriptSometimes when you may use numbers in weak languages, pay attention to converting them into strings.

One, the way to define the regularity

  • 1. Simple and direct definition method (usually this method)

    var reg = /javascript/gi
    
  • 2. Use the object method to create a regular (the use of this method to create the content to be matched is a variable)

    var reg = new RegExp('javascript', gi)
    

Second, the understanding of metacharacters

  • 1. Metacharacters with special meaning
    • \: Escape character, the meaning of the character after the escape
    • ^: Start with a certain metacharacter
    • $: End with a certain metacharacter
    • \n: Matches a newline character
    • . : Any character except \n
    • \o: NUL character (\u0000)
    • \t: Tab character (\u0009)
    • \v: Vertical tab character (\u000B)
    • \f: Form feed character (\u000C)
    • \r: Carriage return (\u000D)
  • 2. Quantifier metacharacters representing the number of occurrences
    • *: Occurs 0 to many times
    • +: Occurs 1 to many times
    • ?: Occurs 0 or 1 time (or greedy when the capture is cancelled)
    • {n}: Appears n times
    • {n,m}: Appears n to m times

Three, the understanding of modifiers

  • x|y: One of x or y
  • [xyz]: One of x or y or z
  • [^xyz]: Any character except xyz
  • [a-z]: Any character between az
  • [^a-z]: Except any one character between az
  • \d: A number between 0-9
  • \D: Any character except the number between 0-9
  • \b: A boundary character
  • \w: Any one of numbers, letters, and underscores
  • \s: Match a blank character, space
  • \S: Matches a non-blank character
  • (): Group, divide a big regularity itself into several smaller regulars, for example var reg = /^(\d+)zhufeng(\d+)$/:;

Four, a few modifiers

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

Five, []the use

  • 1. All characters appearing in square brackets are characters that represent their own meaning (no special meaning)

    var reg = /[.]/ //匹配到.
    var reg = /\./  //匹配到.
    
  • 2. Represents any character

    var reg = /[xyz]/ // 表示匹配x或y或者z
    var reg = /[a-zA-Z]/ // 表示a-z或者A-Z中任意一个
    
  • 3. Brackets do not recognize two digits

    var reg = /^[12]$/; // --> 1或者2中的一个(符合[xyz])
    var reg = /^[12-68]$/; // --> 1、2-6中的一个、8  三个中的一个
    var reg = /^[\d]+$/; // 表示匹配一个或者多少数字
    
  • 4. Invert operation

    var reg = /[^abc]/; // 表示除了abc其它的字符
    

Six, ()the role (similar to mathematics to change the priority of operations)

  • 1. The use of grouping

    var reg = /^18|19$/; // 18、19、181、189、119、819、1819这些都符合
    var reg = /^(18|19)$/; // 只能18或者19
    

Seven, several important methods in regularization

  • 1. The testmethod is used to test whether the given string meets the conditions, return trueorfalse

    var reg = /[x|y]/
    reg.test('|')
    
  • 2. matchGet all the characters that match the regular (simple understanding is to extract the content)

    var str = 'hello JAVA and javascript';
    str.match(/java/gi); // 返回["JAVA", "java"]
    
  • 3. execMatching (step-by-step execution)

    Will return one Array, the first element is the matched element, the second element is the position of the matched element in the string, and the third element is the entire string. If there is no match, it will be returned.null

    var str = 'hello JAVA and javascript';
    var reg = /java/gi;
    reg.exec(str); // 返回["JAVA", index: 6, input: "hello JAVA and javascript"]
    reg.exec(str); // 返回["java", index: 15, input: "hello JAVA and javascript"]
    reg.exec(str); // 返回null
    
  • 4. splitCutting (maybe you will say that the string itself has splita regular merged split)

    'a b   c'.split(' '); // 返回["a", "b", "", "", "c"]
    'a,b, c  d'.split(/[\s\,]+/); // 返回["a", "b", "c", "d"]
    **下面这个是我项目中使用到了,文字高亮**
    var str = 'helloJAVAandjavascript';
    str.split(/(java)/gi); // 返回["hello", "JAVA", "and", "java", "script"],然后再利用标签拼接
    
  • 5. replaceReplacement, a same method is also provided in the string

    • Use string replacement

      var str = 'iceman2016iceman2017';
      str.replace('iceman','shoushou');
      
    • Use regular replacement

      var str = 'iceman2016iceman2017';
      str.replace(/iceman/g, 'shoushou');
      
    • The second parameter can also be a function

      var str = 'iceman2016iceman2017';
      str.replace(/iceman/g, function () {
              
              
          // 第一个参数是正则匹配到的,
          // 第二个参数是如果有分组就是匹配到分组的,如果没有分组匹配到的字符在整个字符中的index
          // 第三个参数是原来的字符
          // 第一次执行匿名函数输出arguments的结果:["iceman", 0, "iceman2016iceman2017"]
          // 第二次执行匿名函数输出arguments的结果:["iceman", 10, "iceman2016iceman2017"]
          console.log(arguments);
          return 'shoushou';
      });
      
    • Notes on the replacesecond parameter

      var str = 'he12llo wo21rd';
      str.replace(/o/g, function (all, letter,) {
              
              
        console.log(all)
        console.log('====',letter) // 返回是6,9
      });
      
      var str = 'he12llo wo21rd';
      str.replace(/(o)/g, function (all, letter,) {
              
              
        console.log(all)
        console.log('====',letter) // 返回是o, o
      });
      
    • replaceUse case (converted to camel case naming)

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

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

8. $1....$9Understanding about

  • 1. ()Represent the meaning of grouping in regular

  • 2. It $means the placeholder after grouping, which 0...9means the serial number after grouping

  • 3. It $1...$9should be ()used in combination with grouping

  • 4. Use case

    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,$6,$7,$8,$9,$10,$11,$12,$13,$14');
    // 返回结果:'a,b,c,d,e,f,g,h,i,j,k,l,m,n'
    
  • 5. Change the hump to the middle line

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

Nine, some cases

  • 1. Match 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)
    
  • 2. Convert numbers to uppercase numbers

    var ary = ['零', '壹', '贰', '叁', '肆', '伍', '陆','柒', '捌', '玖', '拾'];
    '200801'.replace(/\d/g, (args1, args2, args3) => {
          
          
        // 第一个参数的匹配到的数字,第二个参数是匹配到的index,第三个参数的整个字符串
    	console.log(args1, args2, args3)
    	return ary[args1]
    })
    
  • 3. Capitalize the first letter of English

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

    var reg = /^$/
    reg.test(''); // 返回true
    
  • 5. Match a character or start with a space

    var reg = /(^|\\s)(|\\s$)/;
    
  • 6. Currency thousandths

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

Ten, extension points

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

    '.*'.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
    // 输出结果:"\.\*"
    

Guess you like

Origin blog.csdn.net/kuangshp128/article/details/114298501