1. Reference materials

  1. Regular expressions validate urls
  2. Learn about regular expressions in Vue

Second, grammar introduction

Creating a regular expression

Search without logo

var re = /ab+c/;
Copy the code

After the script loads, the regular expression literals are compiled. Better performance can be achieved using this approach when the regular expression remains unchanged.

var re = new RegExp("ab+c");
Copy the code

While the script is running, the regular expressions created with the constructor are compiled. If the regular expression is going to change, or if it is going to be generated dynamically from sources such as user input, you need to use the constructor to create the regular expression.

Advanced search with logo

var re = /pattern/flags;
Copy the code

Example:

var re = /\w+\s/g;
var re = new RegExp("\\w+\\s"."g");
var str = "fee fi fo fum";
var myArray = str.match(re);
console.log(myArray);
Copy the code

Is equivalent to

var re = new RegExp("pattern"."flags");
Copy the code

Example:

var re = new RegExp("\\w+\\s"."g");
var str = "fee fi fo fum";
var myArray = str.match(re);
console.log(myArray);

// ["fee ", "fi ", "fo "]
Copy the code

The modifier

  • I Performs case-insensitive matching.
  • G Perform global matching.
  • M Performs multi-line matching.
  • S allows. To match newline characters.
  • U Matches using patterns of unicode codes.
  • Y Performs a “sticky” search that starts at the current position of the target string.

Special characters

  • Special symbols
    • \ makes the character special or non-special. For example, n becomes a newline \n, and special symbols (becomes a character (.
    • ^ Matches the start of the string.
    • $Matches the end position of the string.
      • Matches the previous subexpression zero to more times.
      • Matches the previous subexpression one to more times.
    • ? Matches the previous subexpression zero to one time.
    • . Matches any single character except the newline character. The newlines are \n and \r.
  • Matching number
    • {n} matches n of the previous subexpression, such that o{2} matches food but not God.
    • {n,} matches at least n of the preceding subexexpressions. For example, o{2,} matches fooooood but not God.
    • {n, m} matches at least n times and at most m times.
  • Match the range
    • X | y match x or y, such as jack | rose can match to the jack and rose, two strings.
    • [xyz] Matches any character in square brackets.
    • [^xyz] Reverse character set that matches any character except those in square brackets.
    • [0-9] The value ranges from 0 to 9.
  • Matching categories
    • \w Find word characters. Word characters include a-Z, A-Z, 0-9, and underscore.
    • \W Finds non-word characters.
    • \d Find numeric characters.
    • \D Find non-numeric characters.
    • \s finds whitespace characters. Whitespace characters include Spaces, \n, \f, \r, \t, \v.
    • \S finds non-whitespace characters.
    • \b matches word boundaries, usually beginning and ending words. For example, /\ BCD/matches cdkey.
    • \B matches non-word boundaries. For example, /\Bcd/ matches abcd.
    • \O finds NULL characters.
    • \n Newline character.
    • \f Page feed character.
    • \r Carriage return.
    • The \t TAB.
    • \v Vertical TAB.
  • grouping
    • (x) captures the parentheses, matches and remembers the match.
    • (? :x) non-capture parentheses, matches do not remember matches. Such as /? :foo){1,2}/, where foo as a whole is matched one or two times.
    • x(? =y) matches x only when x is followed by y. ? =y means that the end of the string is y.
    • x(? ! Y) matches x only when x is not followed by y. ? ! Y means the end of the string is not y.

The RegExp API is introduced

regexObj.test(str)

Returns true if the regular expression matches the specified string; False otherwise.

let str = 'hello world! ';
let result = /^hello/.test(str);
console.log(result);
// true
Copy the code

regexObj.exec(str)

If the match fails, the exec() method returns null and resets lastIndex to 0.

  1. The value is successfully matched once

If the match is successful, the exec() method returns an array (with the additional properties index and input, see table below) and updates the lastIndex property of the regular expression object. The exact matched text is the first item in the returned array, and from the second item, each subsequent item corresponds to the matched text in the capture parentheses in the regular expression

var re = /quick\s(brown).+? (jumps)/ig;
var result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');
/ / the result
/ / /
// 0: "Quick Brown Fox Jumps"
// 1: "Brown"
// 2: "Jumps"
// groups: undefined
// index: 4
// input: "The Quick Brown Fox Jumps Over The Lazy Dog"
// length: 3
// ]
// re.lastIndex 值为 25
Copy the code
  1. Global match, multiple successes (lastIndex is like a cursor)

When a regular expression uses the “g” flag, the exec method can be executed multiple times to find a successful match in the same string. When you do this, the lookup will start at the location specified by the lastIndex property of the regular expression. (Test () also updates the lastIndex attribute). Note that lastIndex will not be reset even if the next lookup is not the original lookup string; it will still start at the recorded lastIndex

var myRe = /ab*/g;
var str = 'abbcdefabh';
var myArray;
while((myArray = myRe.exec(str)) ! = =null) {
  var msg = 'Found ' + myArray[0] + '. ';
  msg += 'Next match starts at ' + myRe.lastIndex;
  console.log(msg);
}
Copy the code

Is equivalent to

var myRe = /ab*/g;
var str = 'abbcdefabh';
// The first time myre.lastindex is 0
var myArray = myRe.exec(str)
var msg = 'Found ' + myArray[0] + '. ';
msg += 'Next match starts at ' + myRe.lastIndex;
console.log(msg);
console.log('myRe.lastIndex', myRe.lastIndex);
// The second time myre.lastindex is 3
var myArray = myRe.exec(str)
var msg = 'Found ' + myArray[0] + '. ';
msg += 'Next match starts at ' + myRe.lastIndex;
console.log(msg);
Copy the code

3. Group matching (regular expressions with parentheses)

Rule description

  • (x) captures the parentheses, matches and remembers the match.
  • (? :x) non-capture parentheses, matches do not remember matches. Such as /? :foo){1,2}/, where foo as a whole is matched one or two times.
  • x(? =y) matches x only when x is followed by y. ? =y means that the end of the string is y.
  • x(? ! Y) matches x only when x is not followed by y. ? ! Y means the end of the string is not y.

Group match

The value of the group is matched in the global variable RegExp.1RegExp. 1RegExp.

const reg = /(https|http):\/{2}w{3}\.(baidu|google|mi|apeland)\.(com|cn)/
const result = reg.test('https://www.baidu.com')
console.log(result) // true
console.log(RegExp. $1)// https
console.log(RegExp. $2)// baidu
console.log(RegExp. $3)// com
Copy the code

Group mismatch

const reg = / (? :https|http):\/{2}w{3}\.(baidu|google|mi|apeland)\.(com|cn)/
const result = reg.test('https://www.baidu.com')
console.log(result) // true
console.log(RegExp. $1)// baidu
console.log(RegExp. $2)// com
console.log(RegExp. $3)// 
Copy the code

4. Introduction to the String API

str.match(regexp)

Refer to the MDN

This method is similar to regexobj.exec (STR)

Method returns a string matching the regular expression.

  1. Match a result

Results: match the first matched value, if there are groups (parentheses), return the results of all groups in the middle, and the last two parameters are the index and the original string respectively

var str = 'For more information, see Chapter 3.4.5.1';
var re = /see (chapter \d+(\.\d)*)/i;
var found = str.match(re);

console.log(found);

// logs ['see Chapter 3.4.5.1',
/ / 'Chapter 3.4.5.1',
/ / '1',
// index: 22,
// input: 'For more information, see Chapter 3.4.5.1']

// 'see Chapter 3.4.5.1' is the whole match.
// 'Chapter 3.4.5.1' is captured by '(Chapter \d+(\.\d)*)'.
// '.1' is the last value captured by '(\.\d)'.
// The 'index' attribute (22) is the index for the entire match from zero.
// The 'input' property is the raw string being parsed.
Copy the code
  1. Matches global (multiple) results

All matching strings are matched and an array is returned

var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/gi;
var matches_array = str.match(regexp);

console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
Copy the code

str.search(regexp)

Returns the position in the string of the first match that satisfies the condition, or -1 if there is no match

function SearchDemo(){
   var r, re;                   // Declare variables.
   var s = "The rain in Spain falls mainly in the plain.";
   re = /falls/i;            // Create a regular expression pattern.
   r = s.search(re);            // Find the string.
   alert(r);
}
Copy the code

str.replace(regexp|substr, newSubStr|function)

Refer to the MDN

Parameters that

  • Regexp (pattern) A Regexp object or its literal
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
// oranges are round, and oranges are juicy.
console.log(newstr);
Copy the code
  • Substr (pattern) A string to be replaced by newSubStr

  • NewSubStr (replacement) is used to replace the part of the string that matches the first argument in the original string

  • Function (replacement) A function that is used to create a new substring. The return value of this function replaces the match of the first argument.

function replacer(match, p1, p2, p3, offset, string) {
  // p1 is nondigits, p2 digits, and p3 non-alphanumerics
  return [p1, p2, p3].join(The '-');
}
// P1, P2, and P3 are regular groups
var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString);  // abc - 12345 - #$*%
Copy the code

Five, the case

Generate regular expressions dynamically

Source of problem: user input keyword search, the keyword of the query results need to be highlighted

The solution:

  1. Generate regular expressions dynamically
  2. Convert keywords into HTML code
  3. Use the replace function

How to dynamically generate regular expressions in Method 2: eval

let regxOther = eval('/'+query+'/g')
Copy the code

Method 1: RegExp

let regx = new RegExp(query, 'g')
Copy the code

Vi. Supplement (Pre-check)

? = Positive forecheck

The first is a number, the second is a meta, matching the first number

? ! = Positive negative forecheck

Preceded by a number (not followed by a meta, and not followed by a number), matches the preceding number

? <= Reverse affirmative precheck

Matches a number preceded by $

? <! Reverse negation precheck

Matches a number that is not preceded by ¥