Home > Article > Web Front-end > JavaScript regular expressions, this article is enough
This article brings you relevant knowledge about javascript, which mainly introduces issues related to regular expressions. Regular expressions are a specific formatting pattern used to verify various Whether the string matches this feature, and then implements advanced text search, replacement, content interception and other operations. I hope it will be helpful to everyone.
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, write this feature according to the syntax of a regular expression to form a The computer program recognizes the pattern (Pattern), and then the computer program will match the text according to this pattern to find the string that conforms to the rules.
The history of the development of regular expressions
The expression form of regular expressions
In development, it is often necessary to complete the search and matching of specified strings based on regular matching patterns.
In addition to retrieving the specified value within the string, the match() method in the String object can also retrieve the specified value in the target string based on The regular match matches all content that meets the requirements. After a successful match, it is saved into an array. If the match fails, false is returned.
In JavaScript applications, 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 let readers better understand the acquisition of regular objects, take matching special characters "^", "$", "*", "." and "\" as an exampleCompare and explain.
Note
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 difference is that 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 characters 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 make it easier for readers to understand the use of character categories, the following uses "." and "\s" as examples for demonstration.
Character set representation: "[]" can implement a character set.
Character range: When used together with the hyphen "-", it means matching 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
The character "-" only represents an ordinary character under normal circumstances, only when it represents a character range
is used as a metacharacter. The range represented by the "-" hyphen follows the order of character encoding. For example, "a-Z", "z-a", and "a-9" are all illegal ranges.
[Case] Limit input content
##Code implementation ideas:
Write HTML, set a text box for year (year) and month (month), and a query button. Get the element object of the operation and verify the submission of the form. Verification year, regular: /^\d{4}/. Verify month, regular rule: / ( ( 0 ? [ 1 − 9 ] ) ∣ ( 1 [ 012 ] ) ) /. The text box gets the focus and removes the color of the prompt box. The text box loses focus, removes whitespace at both ends of the input content, and validates.Code implementation
nbsp;html> <meta> <title>限定输入内容</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><script> function checkYear(obj) { if (!obj.value.match(/^\d{4}$/)) { obj.style.borderColor = 'red'; result.innerHTML = '输入错误,年份为4位数字表示'; return false; } result.innerHTML = ''; return true; } function checkMonth(obj) { if (!obj.value.match(/^((0?[1-9])|(1[012]))$/)) { obj.style.borderColor = 'red'; result.innerHTML = '输入错误,月份为1~12之间'; return false; } result.innerHTML = ''; return true; } var form = document.getElementById('form'); // <form>元素对象 var result = document.getElementById('result'); // <p>元素对象 var inputs = document.getElementsByTagName('input'); // <input>元素集合 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(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); // \uFEFF字节顺序标记;\xA0不换行空白 }; } inputs.year.onblur = function() { this.value = this.value.trim(); checkYear(this); }; inputs.month.onblur = function() { this.value = this.value.trim(); checkMonth(this); }; </script> Methods in the RegExp classtest() method: Check 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 the pattern modifier of the regular object
There are also some properties in the RegExp class that are used to detect the pattern modifier used by the current regular object. , and specify the starting index of the next match, etc.# In order for readers to better understand the use of these attributes, the following will demonstrate the matching of spaces as an example.
search() method: You can return the position where the substring of the specified pattern first appears in the string, relative to 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
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 practice
Password strength verification
Password strength verification conditions:
① Length
②The length is >6 characters and contains one of numbers, letters or other characters. 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".
④The length is >6 characters, and it contains three or more types of numbers, letters or other characters. The password strength is "High".
Ask a question: Match a consecutive character, such as 6 consecutive numbers "458925".
Solution 1: Regular object/\d\d\d\d\d\d/gi.
Existing problems: The repeated "\d" is not easy to read and cumbersome to write.
Solution 2: Use qualifiers (?, ,*, { }) to complete the 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 supports greedy matching and lazy matching when matching any character within a specified range.
In regular expressions, the content enclosed by the bracket characters "()", Call it a "subexpression".
The parentheses implement matching catch and cater, and if the 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.
Capturing: 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.
String对象的replace()方法,可直接利用$n(n是大于0的正整数)获取捕获内容,完成对子表达式捕获的内容进行替换的操作。
可以使用”(?:x)”的方式实现非捕获匹配
在编写正则表达式时,若要在正则表达式中,获取存放在缓存区内的子表达式的捕获内容,则可以使用“\n”(n是大于0的正整数)的方式引用,这个过程就是“反向引用”。
零宽断言:指的是一种零宽度的子表达式匹配,用于查找子表达式匹配的内容之前或之后是否含有特定的字符集。
分类:分为正向预查和反向预查,但是在JavaScript中仅支持正向预查,即匹配含有或不含有捕获内容之前的数据,匹配的结果中不含捕获的内容。
正则表达式中的运算符有很多。在实际应用时,各种运算符会遵循优先级顺序进行匹配。正则表达式中常用运算符优先级,由高到低的顺序如下表。
【案例】内容查找与替换
代码实现思路:
代码实现
nbsp;html> <meta> <title>内容查找与替换</title> <style> p{float:left;} input{margin:0 20px;} </style> <p>过滤前内容:<br> <textarea></textarea> <input> </p> <p>过滤后内容:<br> <textarea></textarea> </p> <script> document.getElementById('btn').onclick = function () { // 定义查找并需要替换的内容规则,[\u4e00-\u9fa5]表示匹配任意中文字符 var reg = /(bad)|[\u4e00-\u9fa5]/gi; var str = document.getElementById('pre').value; var newstr = str.replace(reg, '*'); document.getElementById('res').innerHTML = newstr; }; </script>
相关推荐:javascript学习教程
The above is the detailed content of JavaScript regular expressions, this article is enough. For more information, please follow other related articles on the PHP Chinese website!