JavaScript Study Notes (14) Regular Expressions_Basic Knowledge
RegExp class
The constructor of the RegExp object can take one or two parameters
The first parameter is a pattern string that describes the pattern that needs to be matched. If there is a second parameter, this parameter is specified Additional processing instructions.
1. Basics
1.1 Use the RegExp object
test() method
to test whether it matches. If the given string (only one parameter) matches this pattern, it returns true, otherwise it returns false
var sToMatch = "cat";
var reCat = /cat/; //Regular expression literals use Perl-style syntax
alert(reCat.test(sToMatch) ); //outs "true"
exec() method
has a string parameter and returns an array. The first entry in the array is the first match, the others are backreferences. (That is, there is only one in the array, and it is the first matching one)
var strAAA = "a bat, a Cat, a fAt baT, a faT cat";
var regAt = new RegExp("at", "gi");
var arr = regAt.exec( strAAA); //arr[0] is "at", arr.index value is 3, arr.lastIndex value is 5
match() method
returns a string contained in An array of all matches.
var strAAA = "a bat, a Cat, a fAt baT, a faT cat";
var regAt = new RegExp("at", "gi");
var arrMatch = strAAA.match( regAt); //Note: String.match (the parameter is the matching character) is the opposite of the above
search() method
is somewhat similar to indexOf(), returning the values that appear in the string A matching position. Its parameter is a RegExp object rather than just a substring.
var strAAA = "a bat, a Cat, a fAt baT, a faT cat";
var regAt = new RegExp("at", "gi");
var index = strAAA.search(regAt); //outputs "3" The first occurrence position is 3
1.2 Extended string method
replace() method
can replace the first parameter with the second parameter, and the first parameter here can also be a regular expression Mode.
var strBBB = "The Sky is red.";
//Replace all s in the above sentence and use regular expressions to find all matching
var strNewBBB = strBBB.replace(/ s/gi, "##"); //Replace all "s" (regardless of case) with ##
and then upgrade it. The second parameter can also be a function
var sToChange = "The sky is red.";
var reRed = /red/;
var sResultText = sToChange.replace(reRed, function(sMatch) {
return "blue";
});
alert(sResultText);
In this example, the value of sMatch in the function is always "red" (because this is the only matching pattern). The first occurrence of "red" is replaced with the function's return value "blue".
Append :
I think this is what the sentence in the book "because this is the only matching pattern" means. replace has only two parameters. The first parameter is the only one found. The parameter sMatch of that function should be It is the value of the previous first parameter, the only matching pattern. . .
split() method
var sColor = "red,blue,yellow,green";
var reComma = /,/;
var arrColors = sColor.split(reComma); //split at each comma
alert(arrColors. length); //outputs "4"
There must be a backslash before the comma in the regular expression reComma, because the comma has a special meaning in the grammar and must be escaped.
2. Simple mode
2.1 Metacharacters
All metacharacters used in regular expressions are:
( [ { ^ $ | ) ? * .
Total 12. Anytime these metacharacters are used they need to be escaped, that is, preceded by a backslash.
Example:
var reQMark = /?/; //Escape
var reQMark=new RegExp("\?"); //You need to pay attention here, double escaping, because the backslash itself is also
needs to be escaped, so we should try to use the first case, literal syntax, in the future! Perl style
2.2 Using special characters
In addition, there are some other predefined special characters, as listed in the following table:
Character Description
------ -----------------------------------------------
t Tab character
n Line feed character
r Carriage return character
f Page feed character
a alert character
e escape character
cX Control character corresponding to X
b Fallback character
v Vertical tab character
The dominant quantifier only attempts to match the entire string. If the entire string does not produce a match, no further attempts are made. In fact, the dominant quantifier is, simply put, one size fits all.
-------------------------------------------------- --------------------------
Description of greed and laziness dominance
------------------ --------------------------------------------------
? ?? ? Zero or one occurrences
* *? * Zero or more occurrences
? One or more occurrences
{n} {n}? {n} Exactly n occurrences
{n,m} {n,m}? {n,m} appears at least n times and at most m times
{n,} {n,}? {n,} appears at least n times
- -------------------------------------------------- ------------------
Look at the example below to better understand the above three quantifiers
var str = "abbbaabbbaaabbb1234";
var reg1 = /.* bbb/g;
var reg2 = /.*?bbb/g;
//var reg3 = /.* bbb/g; //Error reported in Visual Studio2008....
var arrMatches1 = str.match(reg1);
var arrMatches2 = str.match(reg2);
//var arrMatches3 = str.match(reg3);
alert("Greedy:" arrMatches1.join( ",") "nLazy:" arrMatches2.join(","));
The main difference is the matching process!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP regular expression verification: Number format detection When writing PHP programs, it is often necessary to verify the data entered by the user. One of the common verifications is to check whether the data conforms to the specified number format. In PHP, you can use regular expressions to achieve this kind of validation. This article will introduce how to use PHP regular expressions to verify number formats and provide specific code examples. First, let’s look at common number format validation requirements: Integers: only contain numbers 0-9, can start with a plus or minus sign, and do not contain decimal points. floating point

To validate email addresses in Golang using regular expressions, follow these steps: Use regexp.MustCompile to create a regular expression pattern that matches valid email address formats. Use the MatchString function to check whether a string matches a pattern. This pattern covers most valid email address formats, including: Local usernames can contain letters, numbers, and special characters: !.#$%&'*+/=?^_{|}~-`Domain names must contain at least One letter, followed by letters, numbers, or hyphens. The top-level domain (TLD) cannot be longer than 63 characters.

In Go, you can use regular expressions to match timestamps: compile a regular expression string, such as the one used to match ISO8601 timestamps: ^\d{4}-\d{2}-\d{2}T \d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-][0-9]{2}:[0-9]{2})$ . Use the regexp.MatchString function to check if a string matches a regular expression.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The method of using regular expressions to verify passwords in Go is as follows: Define a regular expression pattern that meets the minimum password requirements: at least 8 characters, including lowercase letters, uppercase letters, numbers, and special characters. Compile regular expression patterns using the MustCompile function from the regexp package. Use the MatchString method to test whether the input string matches a regular expression pattern.

PHP Regular Expressions: Exact Matching and Exclusion Fuzzy inclusion regular expressions are a powerful text matching tool that can help programmers perform efficient search, replacement and filtering when processing text. In PHP, regular expressions are also widely used in string processing and data matching. This article will focus on how to perform exact matching and exclude fuzzy inclusion operations in PHP, and will illustrate it with specific code examples. Exact match Exact match means matching only strings that meet the exact condition, not any variations or extra words.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

PHP is a widely used programming language, especially popular in the field of web development. In the process of web development, we often encounter the need to filter and verify text input by users, among which character filtering is a very important operation. This article will introduce how to use regular expressions in PHP to implement Chinese character filtering, and give specific code examples. First of all, we need to clarify that the Unicode range of Chinese characters is from u4e00 to u9fa5, that is, all Chinese characters are in this range.
