Foreword: if you can read this essay, you are sure that you have had more or less contact with re (but still remember how much, only “god” knows). The basic grammar knowledge is put aside first, and we start with the actual programming to verify the four regular operations of re in the browser: verify, slice, extract and replace

Re is used for three purposes

  1. Form validation (looking for characters in a string that match a regular rule) XX if yes, OO if no
  2. Extract the contents of the string (grouping) – Extract and do the following (replace)replaceIs the next operation to extract.)
  3. segmentationsplit

1. Verify

Validation: Looks for characters in a string that match a regular rule. Let’s start with a basic problem

Demo1 Determines whether a string contains “hello” (determines whether a string contains a string)

A method on a String

IndexOf ()

let str = "hello world!";
console.log(str.indexOf("hello") != - 1); // true
// Is not a regular, but is a solution to the current problem,
The indexOf() method returns the indexOf the specified value that first appeared in the call to String, or -1 if the value is not found
Copy the code

Method 2: includes()

let str = "hello world!";
console.log(str.includes("hello")); // true
The // includes() method is used to determine whether one string is included in another string, returning true or false depending on the case
Copy the code

Method 3: Search ()

let str = "hello world!";
console.log(str.search(/hello/) != - 1);
// If you pass in a non-regular expression object,
// It is implicitly converted to a regular expression object using new RegExp(obj)
// Returns the index of the first regular expression match in the string if the match is successful, otherwise -1 is returned
Copy the code

Method 4: Match ()

let str = "hello world!";
console.log(!! str.match(/hello/g));
// If a non-regular expression object is passed in, it is implicitly converted to a RegExp using new RegExp(obj)
// Return the value (array), if the first item is the full string matched, then the result captured in parentheses, if there is no match, return null
// If the regular expression contains the g flag, the method returns an Array containing all matched substrings instead of matching objects
Copy the code

Method on the RegExp object

Method 5: Test ()

let str = "hello world!";
console.log(/hello/.test(str));
// Checks whether the regular expression matches the specified string. Returns true or false
// To find out if a pattern exists in a string, use test() or search
Copy the code

Exec ()

let str = "hello world!";
console.log(!!/hello/.exec(str));
// The exec() method performs a search match in a specified string, returning either a result array or null,
// You can use the regexp.test () method, or the string.search () method, if only to determine whether a match is true or false
Copy the code

Verification summary:

  1. A confirmed (exact match) character looks up whether it is included, usingString. The indexOf () and String. Includes ()
  2. A regular (fuzzy matching) character looks up whether it is included, usingRegExp. Test () and the String. The search ()
  3. Find not recommended, useString. The match () and the RegExp. The exec ()

segmentation

Split: the so-called “split “, is the target string, cut into pieces, in JS use split

The Demo2 target string is “HTML, CSS,javascript”, sliced by commas

let regex = /, /;
let str = "html,css,javascript";
let str2 = "2018/10/18";
console.log(str.split(regex));
console.log(str2.split(/ / / /));
Copy the code

The split() method splits a String into an array of strings using the specified delimiter String to split the String into substrings, confirming the location of each split

The delimiter can be a string or regular expression

extract

Extract: Many times you need to extract partially matched data, usually using group references (group capture)

Demo3 Extract year month day

Method 1: Match ()

let str = "2018-10-18";
let regex = /^(\d{4})\D(\d{2})\D(\d{2})$/;
console.log(str.match(regex));
Copy the code

Method 2: exec()

let str = "2018-10-18";
let regex = /^(\d{4})\D(\d{2})\D(\d{2})$/;
console.log(regex.exec(str));
Copy the code

Method 3: Test ()

let str = "2018-10-18";
let regex = /^(\d{4})\D(\d{2})\D(\d{2})$/;
regex.test(str);
console.log(RegExp. $1.RegExp. $2.RegExp. $3);
Copy the code

Method 4: Search ()

let str = "2018-10-18";
let regex = /^(\d{4})\D(\d{2})\D(\d{2})$/;
str.search(regex);
console.log(RegExp. $1.RegExp. $2.RegExp. $3);
Copy the code

Method 5: Replace ()

let str = "2018-10-18";
let regex = /^(\d{4})\D(\d{2})\D(\d{2})$/;
let date = [];
str.replace(regex, function(match, year, month, day) {
  date.push(year, month, day);
});
console.log(date);
Copy the code

Extract summary: Essentially capture groups recommend use match and exec of these, the most commonly used is match

String.prototype.match(); Arguments: a regular expression object. If passed a non-regular expression object, it is implicitly converted to a RegExp using new RegExp(obj). If you use match() directly to provide any arguments, you get an array of empty strings [“”].

Return value: If the string matches the expression, an array is returned. The first item in the array is the full string that was matched, followed by the result captured in parentheses, or null if there is no match

If the regular expression does not contain the G flag, str.match() returns the same result as regexp.exec (). And the returned Array has an additional input property that contains the original string being parsed, as well as an index property that represents the index of the match result in the original character

If the regular expression contains the G flag, the method returns an Array containing all matched substrings instead of matching objects, and the capture group is not returned (that is, the index and input attributes are not returned). If no match is found, null is returned.

The regexp.exec () method performs a search match in a specified string, returning either a result array or NULL

The main differences between string.match () and regexp.exec ()

  1. Different classes
  2. withgThe relevant
  3. execOnly the first matching string is matched (meaninggDoes not work on it) and all groups are backreferenced, thoughgDoes not take effect on it, but its uselastIndexwhileCycle, can be achievedgThe purpose of this point thanmatchstrong
  4. matchReturns the contents of the array, and the regular expressiongThere is a relationship (if beltg, containing all matching substrings) if nog= = defaultexec

replace

The goal of using a re is usually to match the character of the corresponding rule, and the next step is usually to replace ^_^

Highlight, highlight, highlight, the most powerful API in re processing, because it is often used by pretenders to do some meat business under the guise of substitution

Change Demo4 from YYYY-MM-DD to YYYY/MM/DD

replace

let str = "2018-10-18";
let regex = /-/g;
console.log(str.replace(regex, "/"));
Copy the code

String.replace(); It can be used in two forms, either as a string or as a function

$1,$2… $1,$2… $99 matches 1-99 grouped captured text

Match, $1, $2, index, input function match, $1, $2, index, input function

conclusion

  1. To verify that a string (exact match) is included, useString.indexOf()String.includes()
  2. To verify that a string (fuzzy match) is included, useString.search(),RegExp.test()
  3. To split a string (both acknowledgment and rule characters), useString.split(String/re)
  4. Extract packet capture information, usedString.match(),RegExp.exec()Notice the difference between them ->g
  5. Replace, useString.replace(String/RegExp, string/function)Notice the rule information for the second parameter

Portal -> Regular base method applied

reference

Javascript Regular Expressions Mini-Book