How to quickly get started with VUE3.0: Enter learning
Related recommendations: JavaScript tutorial
Regular expression ( Regular Expression, referred to as regexp )
Application: In project development, functions such as hiding specified digits of mobile phone numbers, data collection, filtering of sensitive words, and form verification can all be implemented using regular expressions.
Applicable fields: In operating systems (Unix, Linux, etc.), programming languages (C, C++, Java, PHP, Python, JavaScript, etc.).
For example: Take text search as an example. If you find a string that matches a certain feature (such as a mobile phone number) in a large amount of text, then write this feature according to the syntax of a regular expression to form a pattern recognized by the computer program ( Pattern), and then the computer program will match the text according to this pattern to find the string that meets the rules.
The history of regular expressions
Expression form of regular expression
During development, it is often necessary to search and match specified strings based on regular matching patterns.
In addition to retrieving the specified value in the string, the match() method in the String object can also match all content that meets the requirements in the target string according to regular rules, and save it to an array after the match is successful. , returns false if the match fails.
In a JavaScript application, you first need to create a regular object before using regular expressions. In addition to the literal creation explained previously, it can also be created through the constructor of the RegExp object.
In order to allow readers to better understand the acquisition of regular objects, a comparative explanation will be given by taking matching the special characters "^", "$", "*", "." and "" as an example .
Note that
although the regular objects created by the constructor method and the literal method are completely identical in function, they have certain differences in syntax implementation. The former pattern needs to escape the backslash () when used. When writing the latter pattern, it should be placed within the delimiter "/", and the flags tag should be placed outside the ending delimiter.
Benefits: Effective use of character categories can make regular expressions more concise and easier to read.
Example 1: Uppercase letters, lowercase letters and numbers can be directly represented using "w".
Case 2: If you want to match numbers between 0 and 9, you can use "d".
In order to facilitate readers' understanding of the use of character categories, the following uses "." and "s" as examples for demonstration.
Representation of character sets: "[]" can implement a character set.
Character range: When used together with the hyphen "-", it means to match characters within the specified range.
Antonym characters: When the metacharacter "^" is used together with "[]", it is called an antonym character.
Not within a certain range: "^" is used together with "[]" to match characters that are not within the specified character range.
Take the string 'get好TB6'.match(/pattern/g) as an example to demonstrate its common usage.
Note
that the character "-" usually only represents an ordinary character and is only
used as a metacharacter when representing a character range. The range represented by the "-" hyphen follows the sequence of character encoding. For example, "aZ", "za", and "a-9" are all illegal ranges.
[Case] Limit input content
Code implementation idea :
Write HTML, set a text box for the year (year) and month (month), and a query button.
Get the element object of the operation and verify the submission of the form.
Verify the year, regular form: /^d{4}/. Verify the month, regular rule: / ( ( 0 ? [ 1 − 9 ] ) ∣ ( 1 [ 012 ] ) ) /.
The text box gets focus and the color of the prompt box is removed. The text box loses focus, removes whitespace at both ends of the input content, and validates.
Code implementation
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Limit input content</title> <style> input[type=text]{width: 40px;border-color: #bbb;height: 25px;font-size: 14px;border-radius: 2px;outline: 0;border: #ccc 1px solid;padding: 0 10px; -webkit-transition: box-shadow .5s;margin-bottom: 15px;} input[type=text]:hover, input[type=text]:focus,input[type=submit]:hover{border: 1px solid #56b4ef; box-shadow: inset 0 1px 3px rgba(0,0,0, .05),0 0 8px rgba(82,168,236,.6); -webkit-transition: box-shadow .5s;} input::-webkit-input-placeholder {color: #999; -webkit-transition: color .5s;} input:focus::-webkit-input-placeholder, input:hover::-webkit-input-placeholder {color: #c2c2c2; -webkit-transition: color .5s;} input[type=submit]{height: 30px; width: 80px; background: #4393C9; border:1px solid #fff;color: #fff;font:14px bolder; } </style> </head> <body> <form id="form"> Year<input type="text" name="year"> Month<input type="text" name="month"> <input type="submit" value="query"> </form> <p id="result"></p> <script> function checkYear(obj) { if (!obj.value.match(/^d{4}$/)) { obj.style.borderColor = 'red'; result.innerHTML = 'Input error, the year is represented by 4 digits'; return false; } result.innerHTML = ''; return true; } function checkMonth(obj) { if (!obj.value.match(/^((0?[1-9])|(1[012]))$/)) { obj.style.borderColor = 'red'; result.innerHTML = 'Input error, month is between 1 and 12'; return false; } result.innerHTML = ''; return true; } var form = document.getElementById('form'); // <form> element object var result = document.getElementById('result'); // <p> element object var inputs = document.getElementsByTagName('input'); // <input> element collection form.onsubmit = function() { return checkYear(inputs.year) && checkMonth(inputs.month); }; inputs.year.onfocus = function() { this.style.borderColor = ''; }; inputs.month.onfocus = function() { this.style.borderColor = ''; }; if (!String.prototype.trim) { String.prototype.trim = function() { return this.replace(/^[suFEFFxA0]+|[suFEFFxA0]+$/g, ''); // uFEFF byte order mark; xA0 does not wrap whitespace }; } inputs.year.onblur = function() { this.value = this.value.trim(); checkYear(this); }; inputs.month.onblur = function() { this.value = this.value.trim(); checkMonth(this); }; </script> </body> </html>The
: detects whether the regular expression matches the specified string.
When the match is successful, the return value of the test() method is true, otherwise it returns false.
Detecting pattern modifiers of regular objects
There are also some properties in the RegExp class that are used to detect the pattern modifiers used by the current regular object and specify the starting index of the next match.
In order for readers to better understand the use of these attributes, the following uses the matching of spaces as an example to demonstrate.
: can return the position where the substring of the specified pattern first appears in the string. It is more powerful than the indexOf() method.
split() method : used to split a string into a string array based on the specified delimiter. The split string array does not include the delimiter.
When there is more than one delimiter, a regular object needs to be defined to complete the string splitting operation.
Note that
when the string is empty, the split() method returns an array "[""]" containing an empty string. If the string and delimiter are both empty strings, an empty array "[] is returned. ".
Hands-on
password strength verification
Password strength verification conditions:
① Length <6 digits, no password strength.
②The length is >6 characters and contains one of numbers, letters or other characters, and the password strength is "low".
③The length is >6 characters and contains two types of numbers, letters or other characters. The password strength is "medium".
④ If the length is >6 characters and contains three or more types of numbers, letters or other characters, the password strength is "High".
asks a question: Matches a consecutive character, such as 6 consecutive digits "458925".
Solution 1: Regular object/dddddd/gi.
Problems: The repeated "d" is not easy to read and cumbersome to write.
Solution 2: Use qualifiers (?, +, *, { }) to complete matching of consecutive occurrences of a certain character. Regular object/d{6}/gi.
When the dot character (.) is used with the qualifier, it can match any character in the specified number range.
Regular expression supports greedy matching and lazy matching when matching any character within a specified range.
In regular expressions, the content enclosed by the bracket characters "()" is called a "subexpression".
Parentheses implement the matching of catch and cater, and if parentheses are not used, it becomes catch and er.
When not grouped, it means matching 2 c characters; after grouping, it means matching 2 "bc" strings.
capture: The process of storing the content matched by a subexpression into the system's cache area.
Non-capturing: Do not store the matching content of the subexpression in the system cache, use (?:x) to achieve this.
The replace() method of the String object can directly use $n (n is a positive integer greater than 0) to obtain the captured content and complete the operation of replacing the content captured by the subexpression.
You can use "(?:x)" to achieve non-capturing matching
When writing a regular expression, if you want to obtain the captured content of the subexpression stored in the cache area in the regular expression, you can use "n" (n is a positive integer greater than 0). Reference, this process is "reverse reference".
Zero-width assertion : refers to a zero-width subexpression matching, used to find whether the content matched by the subexpression contains a specific character set before or after.
Classification: Divided into forward prefetch and reverse prefetch, but only forward prefetch is supported in JavaScript, that is, matching data before it contains or does not contain the captured content, and the matching results do not contain the captured content.
There are many operators in regular expressions. In actual application, various operators will be matched according to the order of precedence. The precedence of commonly used operators in regular expressions, in order from high to low, is as follows.
[Case] Content search and replacement
Code implementation idea :
Code implementation
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Content search and replacement</title> <style> p{float:left;} input{margin:0 20px;} </style> </head> <body> <p>Content before filtering:<br> <textarea id="pre" rows="10" cols="40"></textarea> <input id="btn" type="button" value="filter"> </p> <p>Filtered content:<br> <textarea id="res" rows="10" cols="40"></textarea> </p> <script> document.getElementById('btn').onclick = function () { // Define the content rules that need to be searched and replaced. [u4e00-u9fa5] means matching any Chinese characters var reg = /(bad)|[u4e00-u9fa5]/gi; var str = document.getElementById('pre').value; var newstr = str.replace(reg, '*'); document.getElementById('res').innerHTML = newstr; }; </script> </body> </html>
Related recommendations: JavaScript learning tutorial
. The above is JavaScript regular expressions. This article is enough for the details. For more, please pay attention to other related articles on the PHP Chinese website!