In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "how to use js regular expressions", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use js regular expressions" this article.
A regular expression is a text pattern that includes ordinary characters (for example, letters between an and z) and special characters (called metacharacters). The pattern describes one or more strings to match when searching for text. The RegExp object represents regular expressions and is a powerful tool for performing pattern matching on strings. A regular expression is a lookup and string replacement operation.
Create a new regular expression
Way 1: direct quantity grammar
Var reg = / pattern/attributes
Method 2: syntax for creating RegExp objects
Var reg = new RegExp (pattern, attributes)
Parameter description:
The parameter pattern is a string that specifies the pattern of the regular expression or other regular expression.
The parameter attributes is an optional string with attributes "g", "I", and "m" that are used to specify global, case-sensitive, and multiline matches, respectively. Before ECMAScript standardization, the m attribute was not supported. If pattern is a regular expression, not a string, you must omit this parameter.
The difference between the two is:
1. Regular expression objects newly created with direct quantity syntax are generated when the code is compiled, which is a common way in normal development.
two。 Regular objects generated with constructors are generated when the code is running.
Regular expressions use:
The method of a regular object is used like this: RegExp object. Method (string)
The method of the string object is used like this: string. Method (RegExp object)
Properties and methods of regular objects
Attribute
IgnoreCase returns a Boolean value indicating whether the RegExp object has a flag I
Global returns a Boolean value indicating whether the RegExp object has a flag g
Multiline returns a Boolean value indicating whether the RegExp object has a flag m.
LastIndex an integer that identifies the position of the character to start the next match
Source returns the source text of the regular expression (excluding the backslash)
I perform case-insensitive matching
G performs a global match (looking for all matches instead of stopping after the first match is found).
M performs multiline matching
Regular expression function
It is commonly used for two tasks:
1. Verification
When used for verification, you usually need to add ^ and $before and after to match the entire string to be verified
two。 Search and replace
Whether or not to add this restriction to search / replace depends on the requirements of the search. In addition, it is possible to add\ b instead of ^ and $before and after.
Character class matching
[.] Find any character between square brackets
[^...] Find any characters that are not between square brackets
[aMuz] find any character from lowercase a to lowercase z
[Amurz] find any character from uppercase A to uppercase Z
[Amurz] find any character from uppercase A to lowercase z
. Find a single character, except for line breaks and line Terminators
\ W find word characters, equivalent to [a-zA-Z0-9]
\ W find non-word characters, equivalent to [^ a-zA-Z0-9]
\ s find white space characters
\ s find non-white space characters
\ d find numbers, equivalent to [0-9]
\ d find non-numeric characters, equivalent to [^ 0-9]
\ b match word boundaries
\ r find carriage return
\ t find tabs
\ 0 find NULL characters
\ nLookup newline characters
Repetitive character matching
The previous term should be matched at least n times, but not more than m times.
{n,} match the previous term n or more times
{n} match the previous term n times
N? Match the previous item 0 times or 1 time, that is to say, the previous term is optional, which is equivalent to {0men1}
N + matches the previous item one or more times, which is equivalent to {1,}
N * match the previous item 0 or more times, equivalent to {0,}
N $matches any string that ends with n
^ n matches any string that starts with n
? = n matches any string immediately followed by the specified string n
?! n matches any string that is not followed by the specified string n
Match a specific number
^ [1-9]\ d match positive integers
^-[1-9]\ d matches negative integers
^ -? [0-9]\ dmate $match integer
^ [1-9]\ d* | 0$ matches a non-negative integer (positive integer + 0)
^-[1-9]\ d* | 0$ matches non-positive integers (negative integers + 0)
^ [1-9]\ dfloat.\ d* | 0.\ d* [1-9]\ dfloat $matches positive floating point numbers
^-([1-9]\ dfloat.\ d* | 0.\ d* [1-9]\ d*) $matches negative floating point numbers
^ -? ([1-9]\ dnumbers.\ d* | 0.\ d* [1-9]\ d* | 0room.0 + | 0) $matches floating point numbers
^ [1-9]\ dfloat.\ d* | 0.\ d* [1-9]\ d* | 0fol.0 + | 0$ matches non-negative floating point numbers (positive floating point number + 0)
^ (- ([1-9]\ dfloat.\ d* | 0.\ d* [1-9]\ d*)) | 0room.0 + | 0$ matches non-positive floating point numbers (negative floating point numbers + 0)
Match a specific string
^ [A-Za-z] + $matches a string of 26 English letters
^ [Amurz] + $matches a string of 26 English letters in uppercase
^ [amurz] + $matches a string of 26 lowercase letters
^ [A-Za-z0-9] + $matches a string of numbers and 26 letters
^\ w match $matches a string consisting of numbers, 26 letters, or underscores
Method
Test method
Retrieves the value specified in the string. Returns true or false.
Returns true if the string string contains text that matches RegExpObject, otherwise returns false.
Demo1:
If the regular expression has the g modifier, each test method matches from the position where the last match ended.
A regular expression with the g modifier is used to indicate where you want to record each search, and then using the test method, each search starts at the last location where it was matched last time.
Test method var reg = / abc/g; var str = "123abc456abc"; console.log (reg.lastIndex); / / 0 console.log (reg.test (str)); / / true console.log (reg.lastIndex); / / 6 console.log (reg.test (str)); / / true console.log (reg.lastIndex); / / 12 console.log (reg.test (str)); / / false
Demo2:
If the regular expression is an empty string, all strings are matched, but you need to use the new RegExp () method
Test method console.log (new RegExp (''). Test ('abc')); / / true console.log (/' / .test ('abc')); / / false console.log (/' / .test ("'")); / / true
Exec method
The exec () method is used to retrieve the match of a regular expression in a string.
Returns an array containing the matching results. If no match is found, the return value is null.
Demo1:
Exec method var str = "xyz"; var reg1 = / x str; var reg2 = / a str; var res1 = reg1.exec (str); var res2 = reg2.exec (str); console.log (res1); / / ["x", index: 0, input: "xyz"] console.log (res2); / / null
Demo2:
If the regular expression contains parentheses, the returned array contains multiple elements. First, the result of the whole successful match, followed by the result of the successful match in parentheses. If there are multiple parentheses, the result of their successful match will become an array element.
Exec method 2 var str = 'abcdabc'; var reg = / (a) b (c) /; var res = reg.exec (str); console.log (res); / / ["abc", "a", "c", index: 0, input: "abcdabc"]
You have the following two properties for the array returned after calling the exec method:
Input the entire string to be matched
Index the starting position of the whole pattern matching success
Methods of String objects that support regular expressions
Search method
The search () method is used to retrieve a substring specified in a string or to retrieve a substring that matches a regular expression.
Return value: the starting position of the first substring in the stringObject that matches the regexp.
Note: returns-1 if no matching substring is found.
The search () method does not perform global matching, it ignores the flag g. It also ignores the lastIndex attribute of regexp and always retrieves from the beginning of the string, which means that it always returns the first matching position of the stringObject.
Demo:
Search method var str = "abcdcef"; console.log (str.search (/ c _ Unig)); / / 2
Match method
The match () method retrieves the specified value within a string or finds a match of one or more regular expressions. This method is similar to indexOf () and lastIndexOf (), but it returns the specified value instead of the position of the string.
The match method of a string object is similar to the exec method of a regular object:
But if the regular expression has a g modifier, then the match method is different from the exec method:
You can see that match returns all the successful matching results, but the exec method returns only one.
Demo:
Match method var str = "abcd"; var reg1 = / an input; var reg2 = / x reg1; console.log (str.match (reg1)); / / ["a", index: 0, input: "abcd"] console.log (str.match (reg2)); / / null var str = "abcdabc"; var reg = / a str.match g; console.log (str.match (reg)); / / ["a", "a"] console.log (reg.exec (str)) / / ["a", index: 0, input: "abcdabc"]
Replace method
The replace () method is used to replace some characters in a string with other characters, or to replace a substring that matches a regular expression.
Return value: a new string, obtained after replacing the first match or all matches of regexp with replacement.
The replace () method of the string stringObject performs the find and replace operation. It looks for substrings that match regexp in stringObject and replaces them with replacement. If regexp has the global flag g, then the replace () method replaces all matching substrings. Otherwise, it replaces only the first matching substring.
Demo:
The replace method var str = "xxx"; console.log (str.replace ('x charger)); / / yxx console.log (str.replace (/ x charger)); / / yxx console.log (str.replace (/ x charger)); / / yyy
Special character substitution in replace method
Demo:
Replace / / with subexpressions in replace: () in $1 and $2 / / regular expressions is a subexpression, and $1 corresponds to the content of the first expression, that is, java,$2 is script var str = "javascript"; console.log (str.replace (/ (java) (script) /,'$2 $1')) / / output: scriptjava / / $& the string / / regular expression matched by the regular expression is matched by the direct quantity java. If the matching result is java, the value of $& is java, and then replace the matching string var str1 = "javascript" with the string $& -; console.log (str1.replace (/ java/,'$&-')); / / output: java-script var str2 = "javascript" / / $`is the left text of the matching substring ava, then j console.log (str2.replace (/ ava/, "$`)); / / output: jjscript / / $'is the right text of the matching substring ava, then it is script console.log (/ ava/," $'"); / / output: jscriptscript / / $is the direct measure symbol, that is, insert a $symbol console.log (str2.replace (/ ava/," $")) / / output: j$script
The parameter replacement of replace is a function
Match matches the entire string, that is: xyz45678%$& ^
A1 is the first subexpression, ([^\ d] *), which matches 0 or more non-numeric characters, namely: xyz
A2 is the second subexpression, (\ d *), which matches 0 or more numbers, that is, 45678
A3 is the third subexpression ([^\ w] *) that matches 0 or any non-word characters. Equivalent to [^ A-Za-z0-9 _], that is,% $& ^
Index is the position where the pattern match occurs. If the match has been successful from the first character, the position is 0.
String is the string itself, that is, xyz45678%$& ^
Demo:
The parameter replacement of replace is the function function replacer (match, A1, a2, a3, index, string) {return [A1, a2, a3] .join ('~');} var str = 'xyz45678%$& ^'; var reg = / ([^\ d] *) (\ d *) ([^\ w] *) / var res = str.replace (reg, replacer); console.log (res); / / xyz ~ 45678 ~% $& ^
Split method
Split ('regular segmentation of strings', 'return the maximum number of members of the array'); returns the array of partitioned parts
Demo:
The split method var str = 'aforme b, cdjinger; var res = str.split (","); / / split the string console.log (res) with a comma; / / ["a", "b", "c", "d"] var str1 =' aformab, c dhow; var res1 = str1.split (/, * /); / / split the string console.log (res1) with 0 or more commas / / ["a", "b", "", "c", "d"] var str2 ='a, b * /); var res2 = str2.split (/, * /); / / split the string console.log (res2) with 0 or a pair of comma spaces; / / ["a", "b", "c", "d"] var str3 ='a, bline c, d' Var res3 = str3.split (/, * /, 2); / / splits the string with 0 or a pair of comma spaces, while limiting the return array to a maximum of two console.log (res3); / / ["a", "b"]
Regular matching rules can be transformed to split strings.
The following regular matching rule is to split by 0 or more x, and if you add parentheses, the parenthesis matching part, that is, the partition rule, will also be returned as an array member.
Demo2:
Split method 2 var str = "xexamples xxexamples xxexamples @"; var res = str.split (/ xexamples /); / / delimited by 0 or pair x; / / ["", "@"] var res1 = str.split (/ (x*) /) / / if you add parentheses, the parenthesis matching part, that is, the partition rule, will also return console.log (res1) as an array member; / / ["," x "," @ "," @ "," xx "," @ "," xx "," @ "," @ "]
Some applications of regular expressions
1. The character that appears most often in a string
Var re = / (\ w)\ 1scratch _ g
The parentheses outside (\ w) indicate a grouping,\ 1 means to repeat the contents of the first grouping,\ 1 + indicates that the characters matched by\ w are repeated n times, and the following g indicates that all substitutions are performed.
The second parameter of str.replace is a function, parameter a represents the entire matching string, b represents the first capture packet, that is, a single character with repetition, compare a.length with the most repetitive num that has been recorded, if the a.length is larger, assign it to num, record the repeating character b with value, this function returns the replacement text, but there is no return value, that is, replace it with empty Every time this function is replaced, it is executed
The character var str = 'mmmmmmmmaaammmmmmmmmbbbbsccc';function most (str) {var arr = str.split (''); str = arr.sort (). Join (''); / / divides the string by a single character, and then sorts and combines the characters. After this step, the same characters are arranged together var reg = / (\ w)\ 1characters; var num = 0; var value ='' Str.replace (reg, function (a) {/ / console.log (a); if (num)
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.