Home  >  Article  >  Web Front-end  >  JavaScript regular expressions, this article is enough

JavaScript regular expressions, this article is enough

WBOY
WBOYforward
2022-03-21 18:02:362878browse

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.

JavaScript regular expressions, this article is enough

Related recommendations: javascript tutorial

What is a regular expression

regular expression (Regular Expression, referred to as regexp)

  • is a grammatical rule that describes the structure of a string.
  • is a specific formatting pattern used to verify whether various strings match this feature, thereby enabling advanced text search, replacement, content interception and other operations.

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
JavaScript regular expressions, this article is enough

The expression form of regular expressions

  • One is a POSIX specification-compliant regular expression used to ensure portability between operating systems.
  • One is that when Perl (a feature-rich programming language) developed, Perl regular expressions were derived. The regular syntax in JavaScript is based on Perl.

How to use regular expressions

In development, it is often necessary to complete the search and matching of specified strings based on regular matching patterns.

JavaScript regular expressions, this article is enough

exec() method

  • The exec() method is used to search for matches in the target string, returning only one match at a time result.
  • For example, search for abc in the specified string str.

JavaScript regular expressions, this article is enough

  • The "/" in "/abc/i" is the delimiter of the regular expression, and "abc" represents the pattern of the regular expression Text, "i" is a pattern modifier identifier, indicating that case is ignored in str.
  • The parameter of the exec() method is the string str to be matched. When the match is successful, the return value of this method is an array, otherwise null is returned.
  • It can be seen from the return result of exec() that the first element (AbC) saved in the array represents the matched string; the second element index represents that the matched character is located in the target string The index value in (calculated from 0); the third parameter input represents the target string (AbC123abc456).

match() method

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.

JavaScript regular expressions, this article is enough

  • The locator "^" can be used to match the beginning of the string.
  • The locator "$" can be used to match the end of the string.
  • g represents a global match, used to continue searching after the first match is found.

Get the regular object

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.

JavaScript regular expressions, this article is enough

  • pattern is a regular expression pattern text composed of metacharacters and literal characters.
  • Metacharacters are characters with special meanings, such as "^", "." or "*", etc.
  • Text characters are ordinary text, such as letters and numbers.
  • flags represents the pattern modification identifier, which is used to further set the regular expression.

JavaScript regular expressions, this article is enough

  • Mode modifiers can also be used in multiple combinations according to actual needs.
  • For example, if you want to ignore case and match globally, you can use gi directly, and there is no order requirement when writing multiple pattern modifiers.
  • Therefore, the reasonable use of pattern modifiers can make regular expressions more concise and intuitive.

In order to let readers better understand the acquisition of regular objects, take matching special characters "^", "$", "*", "." and "\" as an exampleCompare and explain.

JavaScript regular expressions, this article is enough

  • The selector "|" means "or", and the search condition can be established as long as one of the conditions is met.
  • There is an escaping problem with strings in JavaScript, so the "\" in str in the code represents a backslash "\".
  • When matching special characters in regular expressions, backslashes (\) are also needed to escape the special characters. For example, "\\" becomes "\" after string escape, and then the regular expression uses "\" to match "\".

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

Character category

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".

JavaScript regular expressions, this article is enough

In order to make it easier for readers to understand the use of character categories, the following uses "." and "\s" as examples for demonstration.

JavaScript regular expressions, this article is enough

  • Regular object reg is used to match any two characters after a blank character (except newlines).
  • Therefore, in the results viewed on the console, there is a space before the id.

Character set

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.

JavaScript regular expressions, this article is enough

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

JavaScript regular expressions, this article is enough

##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 = &#39;red&#39;; result.innerHTML = &#39;输入错误,年份为4位数字表示&#39;; return false; } result.innerHTML = &#39;&#39;; return true; } function checkMonth(obj) { if (!obj.value.match(/^((0?[1-9])|(1[012]))$/)) { obj.style.borderColor = &#39;red&#39;; result.innerHTML = &#39;输入错误,月份为1~12之间&#39;; return false; } result.innerHTML = &#39;&#39;; return true; } var form = document.getElementById(&#39;form&#39;); // <form>元素对象 var result = document.getElementById(&#39;result&#39;); // <p>元素对象 var inputs = document.getElementsByTagName(&#39;input&#39;); // <input>元素集合 form.onsubmit = function() { return checkYear(inputs.year) && checkMonth(inputs.month); }; inputs.year.onfocus = function() { this.style.borderColor = &#39;&#39;; }; inputs.month.onfocus = function() { this.style.borderColor = &#39;&#39;; }; if (!String.prototype.trim) { String.prototype.trim = function() { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, &#39;&#39;); // \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 class

test() method: Check whether the regular expression matches the specified string.

JavaScript regular expressions, this article is enough

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.

JavaScript regular expressions, this article is enough

# In order for readers to better understand the use of these attributes, the following will demonstrate the matching of spaces as an example.

JavaScript regular expressions, this article is enough

Methods in the String class

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.

JavaScript regular expressions, this article is enough

  • The parameter of the search() method is a regular object. If a non-regular expression object is passed in, "new RegExp(incoming parameter) will be used )" implicitly converts it to a regular expression object.
  • The return value of the search() method after a failed match is -1.

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.

JavaScript regular expressions, this article is enough

  • # Split according to the "@" and "." delimiters in the string.
  • The parameter of the split() method is the delimiter set by the regular expression mode, and the return value is the split result saved in the form of an array.

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.

JavaScript regular expressions, this article is enough

  • #When using regular matching to split a string, you can also specify the number of string splits.
  • After specifying the number of string splits, if the specified number is less than the number of splits that meet the rules in the actual string, other split results will be ignored in the final return result.

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".

Character Limitation

Character Limitation - Qualifier

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.

JavaScript regular expressions, this article is enough

Character Limitation - Greedy and Lazy Matching

When the dot character (.) is used with the qualifier, it can match any character in the specified number range .

  • Example: "^hello.*world$".
  • Description: It can match a string starting from hello to ending in world and containing zero or more arbitrary characters in the middle.

Regular supports greedy matching and lazy matching when matching any character within a specified range.

  • The so-called greedy means matching as many characters as possible, while lazy means matching as few characters as possible. By default, greedy matching is used.
  • #If you want to achieve lazy matching, you need to add the "?" symbol after the previous qualifier.

JavaScript regular expressions, this article is enough

Bracket characters

In regular expressions, the content enclosed by the bracket characters "()", Call it a "subexpression".

JavaScript regular expressions, this article is enough

Function

JavaScript regular expressions, this article is enough

The parentheses implement matching catch and cater, and if the parentheses are not used, It becomes catch and er

JavaScript regular expressions, this article is enough

. When not grouped, it means matching 2 c characters; after grouping, it means matching 2 "bc" strings.

Capturing and non-capturing

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.

JavaScript regular expressions, this article is enough

String对象的replace()方法,可直接利用$n(n是大于0的正整数)获取捕获内容,完成对子表达式捕获的内容进行替换的操作。

JavaScript regular expressions, this article is enough

  • 第1个参数为正则表达式,用于与str字符串进行匹配,将符合规则的内容利用第2个参数设置的内容进行替换。
  • $2表示reg正则表达式中第2个子表达式被捕获的内容“Capture”。
  • $1表示第1个子表达式被捕获的内容“Regular”。
  • 返回值是替换后的新字符串,因此,并不会修改原字符串的内容。

可以使用”(?:x)”的方式实现非捕获匹配

JavaScript regular expressions, this article is enough

反向引用

在编写正则表达式时,若要在正则表达式中,获取存放在缓存区内的子表达式的捕获内容,则可以使用“\n”(n是大于0的正整数)的方式引用,这个过程就是“反向引用”。

  • “\1”表示第1个子表达式的捕获内容。
  • “\2”表示第2个子表达式的捕获内容,以此类推。

JavaScript regular expressions, this article is enough

  • “\d”用于匹配0~9之间的任意一个数字。
  • 为其添加圆括号“()”后,即可通过反向引用获取捕获的内容。
  • 因此,最后的匹配结果为333和666。

零宽断言

零宽断言:指的是一种零宽度的子表达式匹配,用于查找子表达式匹配的内容之前或之后是否含有特定的字符集。

分类:分为正向预查和反向预查,但是在JavaScript中仅支持正向预查,即匹配含有或不含有捕获内容之前的数据,匹配的结果中不含捕获的内容。

JavaScript regular expressions, this article is enough

正则运算符优先级

正则表达式中的运算符有很多。在实际应用时,各种运算符会遵循优先级顺序进行匹配。正则表达式中常用运算符优先级,由高到低的顺序如下表。

JavaScript regular expressions, this article is enough

【案例】内容查找与替换

JavaScript regular expressions, this article is enough

代码实现思路

  • 编写HTML,定义两个文本域,一个用于用户输入,另一个用于显示按照要求替换后的过滤内容。
  • 用户输入只要含有bad和任意中文字符,就利用*替换。
  • 查找并替换的内容规则:/(bad)|[\u4e00-\u9fa5]/gi。

代码实现

	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(&#39;btn&#39;).onclick = function () {
	// 定义查找并需要替换的内容规则,[\u4e00-\u9fa5]表示匹配任意中文字符
	var reg = /(bad)|[\u4e00-\u9fa5]/gi;
	var str = document.getElementById(&#39;pre&#39;).value;
	var newstr = str.replace(reg, &#39;*&#39;);
	document.getElementById(&#39;res&#39;).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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete