Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What should be paid attention to when using pattern in JavaScript

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces what you need to pay attention to when using pattern in JavaScript, the content is very detailed, interested friends can refer to it, I hope it can be helpful to you.

Creation of RegExp objects:

A regular regular expression can be created with a direct amount, that is, characters enclosed by a slash "/". However, in an environment where parameter variation is required, the RegExp () constructor is a better choice:

Var reg1 = /'\ wobblemp /'\ wxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Comparing the two creation methods, the first parameter in RegExp is the regular string to be created. On the one hand, note that because it is not a representation of a direct quantity, there is no need to enclose the slash "/"; instead, the quotation marks "'" and the escape symbol "\" must be escaped twice in the string.

In addition, both the direct quantity and the RegExp () constructor generate a new RegExp object and assign it to the variable.

As mentioned in the Javascript authoritative Guide, for the direct quantity of a regular expression, ECMAscript 3 states that the same RegExp object will be returned every time it is used, so regular expressions created with direct quantities will share an instance. It was not until ECMAScript 5 that a different instance was returned each time.

Among browsers, IE always follows the rules of ECMAScript 5, while older versions of other browsers follow the rules of ECMAScript 3. Therefore, in practical application, it is safer to use the method of constructor creation, or remember to return to 0 when using the lastIndex attribute.

Use of parentheses ():

1. Grouping

That is, the combination of individual items into subexpressions is processed uniformly, which is generally used for? Repetitive processing of, +, *, {nrecom}, etc. See examples:

Var reg = / Java (script)? /

The script is processed uniformly in the formula.

2. Backward citation

That is, the text that matches in the preceding parentheses in the citation with "\ n" (n represents the serial number of the reference) in the regular expression. See examples:

Var reg = / (\ d +) [amurz] {3}\ 1Universe; / / 20man20//20man23 error / / reg = /\ 1 [Amurz] {3} (\ d +) /; wrong

Note that "\ n" refers to the previously matched text "20", not the matching regular expression "\ d +". In addition, JS can only reference the previous matching text, as in the example, write\ 1 in front of the parenthesis reference, will not match any text, the browser will prompt an error. Similarly, reference naming conventions such as "(? exp)" (exp is a regular character) are not supported in JS, only numeric references are supported.

Now that grouping and references are mentioned, if you only want to group and not reference, you can use the form of "(?: exp)", which neither matches the text nor gives the reference number. See examples:

Var reg = / (\ w {3}) (?:\ d +) ([amurz] {2})\ 2Greater hand hand 7788abab

Obviously\ 2 matches "ab" instead of "7788". This facilitates grouping processing and speeds up the efficiency of the query.

3. Subpattern matching

Sometimes we want to refer directly to the text that operates parenthesis matching, then we can use the subpattern matching feature (called subpattern matching in the authoritative guide, which is a bit awkward, actually replacing the matching text with a variable form). The basic form is to replace the text with the matching number n with the form of'$n', which is commonly used in the replace () method in the String object. See the example where words are exchanged on both sides of the equal sign:

Var reg = / (\ w +) = (\ w +) /; var str = 'love=hate';str.replace (reg,'$2=$1'); / / "hate=love"

Order, greed, laziness:

General repetitive matching characters such as? In the process of matching, the greedy matching method is adopted, that is, matching as many characters as possible. The corresponding is lazy matching, that is, as few matching results as possible, and the form can be used simply by adding a question mark after the repeated matching characters, such as? , +? , *? 、 {n,m}? . See examples:

Var str = 'goooogle';var reg1 = / oiled go; / / "goooo" var reg2 = / oiled impulse; / / "go"

Now make a slight change to the example:

Var str = 'goooogle';var reg1 = / oooogle; / / "oooogle" var reg2 = / oiled oooogle

The result of the modified example becomes the same. Why doesn't / o+?gle/ match to "ogle"? The original regular expression always matches from left to right, and the substring is not obtained from the right to match.

Although the above results are the same, the principle of matching is not quite the same. In reg1, first o + matches all "o", followed by "gle" to complete the overall match. And in reg2, oasis? A "o" is matched first, and then gle fails to match in bits 2 to 4 of the string (that is, the "ooo" of the original string). And then go back to oasis? To match the second "o", and then match "gle" in the 3rd to 4th position after success, and so on. Finally, it matches the entire string.

In general, keep in mind that in terms of priority, order matching from left to right > greedy / lazy matching.

Zero width assertion:

For an overall explanation of zero-width assertions, please refer to the blog article "30-minute introduction to regular expressions". It is worth noting that only zero-width antecedent assertions are supported in JS. That is, zero width positive prediction advance assertion "(? = exp)" and zero width negative prediction advance assertion "(?! exp)".

The so-called "zero width" means that it does not occupy space in the matching result characters. For example, "\ w" and "\ s" will occupy one or more spaces, depending on the matching character length. The corresponding positions such as "^" and "$" do not occupy space, and zero width belongs to this category.

The so-called "positive / negative prediction" refers to the situation that is required to be satisfied in the assertion. "positive" means to satisfy the exp, and "negative" means to satisfy the exp.

The so-called "go first" means that the matched string comes first and the zero-width assertion follows. That is, whether the latter part of the string satisfies the assertion.

The so-called "assertion" is the condition of judgment.

Look at two examples of zero-width assertions:

Var str = 'java coffeescript';var reg1 = /\ b\ w + (? = script\ b) /; / / coffee var reg2 = /\ b\ w + (?! script\ b) /; / / java

Reg1 is zero width positive prediction advance assertion, "(? = script\ b)" indicates that a word needs to end with "script", which represents a condition that does not take up any space.

Similarly, reg2 predicts negative predictions of zero width, and "(?! script\ b)" indicates a word that does not end with "script".

In addition, because there is no zero-width backward assertion, it is not possible to determine what conditions are satisfied in the first part of a string. However, in JS, you can use multiple regular expressions: first match the string you are looking for, then intercept the character string that begins with index, and then match whether the end of the substring meets the desired assertion condition. The specific usage can be tried separately.

Similarities and differences between match () and exec ():

Match and exec are common ways for regular expressions to match strings. The functions of the two are similar, with some slight differences:

1. Mode of use

Match is a method of wrapping an object in a string, usage: String.match (RegExp)

Exec is a method of a regular expression object, usage: RegExp.exec (String)

2. Returned result

When RegExp does not set the global flag "g":

The return results of both are the same. That is, null is returned if there is no matching value, and an array (array) is returned if there is a matching value. Array [0] is a matching string, array [1], array [2]... Then it corresponds to the substrings $1, $2 matched by parentheses in the regular expression. At the same time, the array has two attributes, array.index represents the initial position of the matching string and array.input represents the string being retrieved.

When RegExp has set the global flag "g":

Match returns an array array when it has a value. Each item of the array in turn represents all the matched strings, so there are no more parenthetical matching substrings. At this point, the array has no index attribute and no input attribute.

The performance of exec is no different from that without a global label "g". At this point, the array array,array [0] is the currently matched string, array [1], array [2]... The string that matches the parentheses under the current match. Notice at this point that the lastIndex property of the RegExp object represents the last position at the end of the matching string in the original string. When there is no further match, the lastIndex property is set to 0. Therefore, you can use lastIndex's loop to find all matching strings. Take a look at the example:

Var str ='I love1 my job22';var reg = /\ b [a-z] + (\ d +)\ b array = str.match (reg); / / array = ["love1", "job22"] / / array.index = undefind//array.input = undefined--array = reg.exec (str) / / array = ["love1", "1"] / / array.index = 2//array.input = "I love1 my job22" / / reg.lastIndex = 7//run againreg.exec (str); / / array = ["job22", "22"] / / array.index = 11//array.input = "I love1 my job22" / / reg.lastIndex = 16//run againreg.exec (str); / / reg.lastIndex = 0

Finally, considering the version differences between ECMAScript 3 and ECMAScript 5, remember to manually set the lastIndex property of the RegExp object to 0 after each match to meet the requirements of old non-IE browsers.

Js regular expressions, pattern, considerations

In a word, please use, /\ wproof +\ w+ (\. +\ w+) {1,} / .test (str) to verify, do not use "\ wrought +\ w+ (\. +\ w+) {1,}" .test (str) to verify.

Using the latter, directly, you can pass the verification with add@dfddf.

On the use of pattern in JavaScript need to pay attention to what matters to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report