When writing programs or web pages that process strings, there is often a need to find strings that meet certain complex rules. Regular expressions are a tool used to describe these rules. In other words, regular expressions are codes that record text rules.
Users have most likely used the wildcard characters used for file search in Windows, that is, * and? . If you want to find all Word documents in a certain directory, users can search for *.doc. Here, * is interpreted as an arbitrary string. Similar to wildcards, regular expressions are also tools used for text matching, but they can more accurately describe the user's needs than wildcards. Of course, the cost is more complexity. For example, the user can write a regular expression to Find all strings starting with -0, followed by 2-3 digits, then a hyphen "-", and finally a 7- or 8-digit string (such as 0010-12345678 or 0376-7654321).
Regular expressions are suitable for text matching tools, so this article has mentioned searching/finding in a string many times. This means that in a given string, search and find The matching part of a certain regular expression. It is possible that no part of the string satisfies the given regular expression, in which case each such part is called a match.
In general, regular expressions have the following three functions:
(1) Test a certain pattern of a string. For example, you can enter a string and test to see if there is a phone number pattern or a credit card pattern in the string, which becomes a validity check for the data.
(2) Replacement text. You can use a regular expression to represent specific text in the document, and then delete it entirely or replace it with other text.
(3) Extract a substring from the string based on pattern matching. Can be used to find specific words in text or input fields.
A regular expression is a text pattern composed of ordinary characters (such as characters a-z) and special characters (also called metacharacters). This template describes one or more characters to match when searching for text bodies. Regular expressions serve as a template to match a character pattern to a searched string.
The syntax of the regular expression is as follows:
/Pattern of matching object/
Among them, the part between them is what will be in the target string The pattern to match. When using it, users only need to put the content of the matching object template they want to find between the "//" delimiters.
For example, to find the matching pattern Test in the string "TestDemo", you can use the following code:
/Test/