In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about the example analysis of JS regular expressions, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Regular expressions can:
1. Test a pattern of the string. For example, you can test an input string to see if there is a phone number pattern or a credit card number pattern in the string. This is called data validation.
2. Replace the text. You can use a regular expression to identify specific text in a document, and then you can delete it all or replace it with other text
3. Extract a substring from the string according to pattern matching. Can be used to find specific text in text or input fields
Regular expression Grammar A regular expression is a text pattern consisting of ordinary characters (such as characters a to z) and special characters (called metacharacters). The pattern describes one or more strings to be matched when finding the body of the text. The regular expression acts as a template that matches a character pattern with the searched string.
Create a regular expression
Var re=new RegExp (); / / RegExp is an object, like Aarray / / but has no effect. You need to pass the contents of the regular expression into re=new RegExp ("a") as a string; / / the simplest regular expression matches the letter a re=new RegExp ("a", "I"); / / the second parameter indicates that the match is case-insensitive.
The first argument of the RegExp constructor is the text content of the regular expression, while the second argument is an optional flag. Flags can be combined
G (full-text lookup) I (ignore case) m (multiline lookup)
Var re = new RegExp ("a", "gi"); / / matches all an or A
Regular expressions have another way to declare the literal quantity of regular expressions.
Var re = / a/gi
The method of regular expression object
Test, which returns a Boolean value indicating whether a pattern exists in the string being looked up. Returns true if it exists, false otherwise. Exec, which runs a lookup in a string using a regular expression pattern and returns an array containing the results of the lookup. Compile, which compiles regular expressions to an internal format for faster execution. Properties of a regular expression object
/ / test method, which tests the string and returns true if it matches the pattern, otherwise returns falsevar re = / he/;// the simplest regular expression, which matches the word he var str = "he"; alert (re.test (str)); / / true str = "we"; alert (re.test (str)); / / false str = "HE"; alert (re.test (str)) / / false, uppercase, if you want to match both uppercase and lowercase, you can specify the I flag (I is the representation of ignoreCase or case-insensitive) re = / he/i; alert (re.test (str)); / / true str = "certificates he loves her!"; alert (re.test (str)); / / true, as long as it contains he (HE). If it is only he or HE and there are no other characters, you can use ^ and $re = / ^ he/i. / / delimited (^) represents the character start position alert (re.test (str)); / / false, because he is not at the beginning of str str = "He is a good boy!"; alert (re.test (str)); / / true,He is the character start position, and you also need to use $re = / ^ he$/i;//$ to indicate the character end position alert (re.test (str)); / / false str = "He"; alert (re.test (str)) / / true / / of course, you can't find out how powerful regular expressions are, because we can use = = or indexOf re = /\ s in the above example to match any white space characters, including spaces, tabs, page feeds, etc. Str= "user Name"; / / user name contains spaces alert (re.test (str)); / / true str= "user Name" / / the user name contains the tabs alert (re.test (str)); / / true re=/ ^ [Amurz] / ibank / [] matches any character within the specified range, where it matches the English alphabet and is not case-sensitive to str= "variableName"; / / the variable name must begin with the letter alert (re.test (str)); / / true str= "123abc"; alert (re.test (str)); / / false
Of course, it's not enough to know whether the string matches the pattern. We also need to know which characters match the pattern.
Var osVersion = "Ubuntu 8"; / / where the 8 represents the system major version number var re = / ^ [a murz] +\ s +\ d represents a numeric alert (re.test (osVersion)). / / true, but we want to know the major version number / / another method, exec, which returns an array. The first element of the array is the complete matching content re=/ ^ [a murz] +\ s +\ d matching osVersion I; arr = re.exec (osVersion); alert (arr [0]); / / output the osVersion in its entirety, because the whole string just matches re / / I only need to fetch the number re\ dhands / Var arr = re.exec (osVersion); alert (arr [0]); / / 8
More complex usage, using sub-matching
The first to n elements of the array returned by / / exec contain any sub-match that occurs in the match re=/ ^ [amurz] +\ s + (\ d +) $/ I _ match / use () to create a sub-match arr = re.exec (osVersion); alert (arr [0]); / / the whole osVersion, that is, the complete matching alert of the regular expression (arr [1]) / / 8, the first child matches, in fact, you can also take out the major version number alert (arr.length); / / 2 osVersion = "Ubuntu 8.10"; / / take out the major version number and the minor version number re = / ^ [a murz] +\ s + (\ d +)\. (\ d +) $/ I hand. Is one of the metacharacters of regular expressions. To use its literal meaning, you must escape arr = re.exec (osVersion); alert (arr [0]); / / full osVersion alert (arr [1]); / / 8 alert (arr [2]); / / 10
Note that when the string does not match re, the exec method returns null
Some methods related to regular expressions for String objects
/ / replace method to replace the string var str = "some money"; alert (str.replace ("some", "much")); / / much money / / replace the first parameter can be the regular expression var re = /\ s var re / white space character alert (str.replace (re, "%")) / / some%money / / regular expressions are extremely convenient when you don't know how many white space characters are in a string: str = "some some\ tsome\ t\ f"; re = /\ sblank; alert (str.replace (re, "#")) / / but this will only replace the pile of white space characters that appear for the first time / / because a regular expression can only be matched once.\ s + after matching the first space, it exits re = /\ s white space, the global flag, which makes the regular expression match the entire string alert (str.replace (re, "@"). / / some@some@some@ / / another similar is split var str = "a-bd-c"; var arr = str.split ("-"); / / return ["a", "bd", "c"] / / if the str is entered by the user, he may enter a-bd-c or abdc or a_bd_c, but it will not be abdc (so he mistyped) str = "a_db-c" / / the user adds the delimiter s re=/ [^ a murz] / iTabash / before we say ^ indicates the beginning of the character, but in [] it represents a negative character set / / matches any character that is not within the specified range, here it matches all characters except letters arr = str.split (re); / / still returns ["a", "bd", "c"] / / We often use indexOf when looking in a string, and the method applied to regular search is search str = "My age is 18.Golden age!"; / / the age is not fixed, we can't find its location with indexOf re = /\ dcalendar alert; alert (str.search (re)) / / return the found string starting subscript 10 / / Note, because the search itself is returned as soon as it appears for the first time, there is no need to use the g flag / / in search. Although the following code does not make an error, the g flag is redundant re=/\ dstring re g; alert (str.search (re)); / / it is still 10
Note that when the search method does not find a match, it returns-1
Similar to the exec method, the match method of the String object is also used to match a string with a regular expression and return an array of results
Var str = "My name is CJ.Hello everyone!"; var re = / [Amurz] /; / / matches all uppercase letters var arr = str.match (re); / / returns the array alert (arr); / / the array contains only one M because we do not use global matching re = / [Amurz] / g; arr = str.match (re); alert (arr) / / the word re = /\ b [a-z] *\ bbind is extracted from the string and the word boundary is str = "one two three four"; alert (str.match (re)); / / one,two,three,four
Some properties of RegExp object instance
Var re = / [a murz] / I; alert (re.source); / / output the [amerz] string / / Please note that the direct alert (re) outputs the regular expression along with the forward slash and flag, which is defined by the re.toString method
The instance of each RegExp object has the lastIndex property, which is the start position of the next successful match in the looked up string, with a default value of-1. The lastIndex property is modified by the exec and test methods of the RegExp object. And it is writable.
Var re = / [Amurz] /; / / after the exec method is executed, modify the lastIndex property of re, var str = "HelloGravity Worldweights!"; var arr = re.exec (str); alert (re.lastIndex); / / 0, because the global flag re = / [Amurz] / g; arr = re.exec (str); alert (re.lastIndex); / / 1 arr = re.exec (str); alert (re.lastIndex); / / 7
When the match fails (there is no match later), or when the lastIndex value is greater than the string length, executing methods such as exec will set the lastIndex to 0 (start position)
Var re = / [A Mel Z] /; var str = "HelloMagneWorldCandlers!"; re.lastIndex = 120; var arr = re.exec (str); alert (re.lastIndex); / / 0
Static properties of the RegExp object
/ / the last string used to match (the string passed to the test,exec method) var re = / [Amurz] /; var str = "var arr re.exec (str); alert (RegExp.input); / / Hellother Worldhands! Re.exec ("tempstr"); alert (RegExp.input); / / is still HelloGrad Worldword matching characters, because tempstr does not match / / lastMatch's last matching character re = / [aripz] / g; str = "hi"; re.test (str); alert (RegExp.lastMatch); / / h re.test (str); alert (RegExp ["$&"]); / / I $& is the short name of lastMatch, but because it is not a legal variable name. / / the last matching packet of lastParen re = / [a Murz] (\ d +) / gi; str = "Class1 Class2 Class3"; re.test (str); alert (RegExp.lastParen); / / 1 re.test (str); alert (RegExp ["$+"]) / / 2 / / leftContext returns the characters in the searched string from the beginning of the string to the position before the last match / / rigthContext returns the characters in the searched string between the beginning of the last matching position and the end of the string re = / [Amurz] / g; str = "123ABC456"; re.test (str); alert (RegExp.leftContext); / / 123 alert (RegExp.rightContext); / / BC456 re.test (str) Alert (RegExp ["$`]); / / 123A alert (RegExp [" $'"]); / / C456
The multiline property returns whether the regular expression uses multiline mode, this property is not for a regular expression instance, but for all regular expressions, and this property is writable. (IE and Opera do not support this property)
Alert (RegExp.multiline); / / because IE,Opera does not support this attribute, it is best to specify var re = /\ wsquash m separately; alert (re.multiline); alert (RegExp ["$*"]); / / the static property of the RegExp object does not change RegExp.multiline = true;// because the m flag is assigned to an object instance of RegExp, which opens the multiline matching pattern alert (RegExp.multiline) for all regular expression instances.
Note when using metacharacters: metacharacters are part of regular expressions and must be escaped when we want to match regular expressions themselves. Here are all the metacharacters used in the regular expression ([{\ ^ $|)? * +.
Var str = "?"; var re = /? /; alert (re.test (str)); / / error because? Is a metacharacter and must escape re = /\? /; alert (re.test (str)); / / true
Note using the RegExp constructor and using regular expression literals to create regular expressions
Var str = "\?"; alert (str); / / only output? Var re = /\? / / will match? Alert (re.test (str)); / / true re = new RegExp ("\?"); / / error, because this is equivalent to re = / re = new RegExp ("\?"); / / correct, will match? Alert (re.test (str)); / / true
Since double escape is so unfriendly, it is still declared in the literal quantity of regular expressions.
How do I use special characters in regular expressions?
/ / the ASCII method uses hexadecimal numbers to represent the special characters var re = / ^\ x43\ x4A / will match CJ alert (re.test ("CJ")); / / true / / can also use octal mode re = / ^\ 103\ 112 $/; / / will match CJ alert ("CJ"); / / true / / you can also use Unicode encoding re = / ^\ u0043\ u004A$/ / / to use Unicode, you must start with u, followed by the four-bit hexadecimal representation of character encoding alert (re.test ("CJ"))
In addition, there are other predefined special characters, as shown in the following table: character description\ nnewline character\ r carriage return\ t tab\ f feed character (Tab)\ cX control character corresponding to X\ b backspace character (BackSpace)\ v vertical tab null character ("")
Character class-- > simple class, reverse class, scope class, combination class, predefined class
/ / simple class var re = / [abc123] /; / / will match one of the six characters of abc123 / / negative class re = / [^ abc] /; / / will match one character except abc / range class re = / [Amurb] /; / / will match 26 letters of lowercase Amurb re = / [^ 0-9] / / / A character to be matched by 10 characters from 0 to 9 / / the combinatorial class re = / [a-b0-9A murazz] /; / / will match letters, numbers and underscores
Predefined class
The code is equivalent to a match. Under IE [^\ n] Other [^\ n\ r] match any character except newline character\ d [0-9] match number\ D [^ 0-9] match non-numeric character\ s [\ n\ r\ t\ f\ x0B] match a blank character\ S [^\ n\ r\ t\ f\ x0B] match a non-white space character\ w [a-zA-Z0-9] Match alphanumeric and underscore\ W [^ a-zA-Z0-9 _] to characters other than alphanumeric underscore
Quantifier (the quantifier in the following table is greedy when a single quantifier appears) the code description * matches the previous subexpression zero or more times. For example, zo* can match "z" and "zoo". * is equivalent to {0,}. + matches the previous subexpression one or more times. For example, 'zo+' can match "zo" and "zoo", but not "z". + is equivalent to {1,}. ? Matches the previous subexpression zero or once. For example, "do (es)?" Can match "do" in "do" or "does". ? It is equivalent to {0jue 1}. {n} n is a non-negative integer. Match the determined n times. For example,'o {2} 'does not match the' o'in 'Bob', but does match the two o in 'food'. {n,} n is a non-negative integer. Match at least n times. For example,'o {2,} 'does not match' o'in 'Bob', but does match all o in 'foooood'. O {1,}'is equivalent to 'oasis'. O {0,}'is equivalent to 'oval'. {n ·m} m} m and n are non-negative integers, where n
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.