In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "js regular expression summary". In daily operation, I believe many people have doubts about js regular expression summary. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "js regular expression summary". Next, please follow the editor to study!
Var reCat = new RegExp ("cat", "gi"); / / the RegExp constructor can take one or two arguments, the first parameter describing the pattern string to be matched, and the second parameter specifying the additional processing command var reCat = / cat/gi / / use Perl-style syntax I: perform case-insensitive matching g: perform global matching (find all matches instead of stopping after the first match is found) m: perform multiline matching
Metacharacter
Metacharacters are part of expression syntax. All metacharacters used in regular expressions are: {[(\ ^ $|)]}? * +-
If it matches a question mark: var reQMark = /\? /; or var reQMark = new RegExp ("\\?"); / / notice that there are two backslashes and a double escape.
\ xxx finds the character specified by the octal number xxx, such as: /\ 142 / for the character b\ xdd finds the character specified by the hexadecimal number dd, such as: /\ x62 / finds the Unicode character specified by the hexadecimal number xxxx Such as: /\ u0062 / find carriage returns for the character b\ r find line feed\ f find feed\ t find tabs\ v find vertical tabs\ a find alert characters\ e find escape characters\ cX find control characters corresponding to X\ 0 find NULL characters. Finding a single character, except for line breaks and line Terminators, is equivalent to [^\ n\ r]\ w finding word characters, equivalent to [a-zA-Z_0-9]\ W finding non-word characters, equivalent to [^ a-zA-Z_0-9]\ d finding numbers, equivalent to [0-9]\ D looking for non-numeric characters, equivalent to [^ 0-9]\ s looking for blank characters. Equivalent to [\ t\ n\ x0B\ f\ r],\ x0B is vertical tab like\ t\ s to find non-white space characters, equivalent to [^\ t\ n\ x0B\ f\ r]
Square bracket
[abc] find any character between square brackets [^ abc] find any character not between square brackets [0-9] find any number from 0 to 9 [Amurz] 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 [adgk] find any character within a given set [^ adgk] find any character outside a given set
Quantifier
? Match any string that contains zero or one, such as: ba?d matches bd, bad
+ match any string that contains at least one, such as: ba+d matches bad, baad
* match any string containing zero or more, such as: ba*d matches bd, bad, baad
{n} matches a string that contains a sequence that occurs exactly n times, such as: ba {1} d matches bad
{n ba m} matches strings containing sequences at least n times but not more than m times, such as bd and bad.
{n,} matches strings that contain sequences that appear at least n times, such as: ba {0,} matches bd, bad, baad, baaad
Greedy quantifier: first look at whether the whole string matches. If no match is found, the last character in the string last year and try again, such as:?, +, *, {n}, {n, m}, {n,}. The default is greedy quantifier.
Inert quantifier: first look at whether the first letter in the string matches. If this character alone is not enough, read the next character to form a two-character string, which is the opposite of the greedy quantifier, such as:?, +?, *, {n}, {n, m}, {n,}?
Dominant quantifier: only try to match the whole string. If the whole string cannot produce a match, no further attempt is made, such as:? +, + +, * +, {n} +, {n, m} +, {n,} +
Var sToMatch = "abbbaabbbaaabbb1234"; var re1 = / .* bbb/g; / / the matching result is "abbbaabbbaaabbb" var re2 = / .*? bbb/g; / / only the inert quantifier can match successfully, and the matching result is "abbb", "aabbb", "aaabbb" var re3 = /. * + bbb/g; / /, and the error is reported directly.
Grouping of complex patterns: used by a series of parentheses surrounding a series of characters, character classes, and quantifiers
/ (dog) {2} / match "dogdog"
/ ([bd] ad?) * / match null, "ba", "da", "bad", "dad"
/ (mom (and dad)?) / match "mom", "mom and dad"
/ ^\ s* (. *?)\ blank characters / matches the white space characters at the beginning and the end, or you can use / ^\ s+ |\ smatching characters
Backreference to complex patterns: also known as captive grouping, created and numbered in the order of left parenthesis characters encountered from left to right, such as expressions (A? (B? (C?) Three backreferences numbered from 1 to 3 will be generated: (a? (B? (C?)), (B? (C?)), (C?)
Backreferences can be used in several different ways:
First, after using the test (), match (), or search () methods of the regular expression object, the value of the backreference can be obtained from the RegExp constructor, such as:
Var sToMatch = "# 123456789"; var reNumbers = / # (\ d +) /; reNumbers.test (sToMatch); alert (RegExp.$1); / / "123456789", $1 saves the first backreference, and you can use $2.
You can then include back references directly in the expression that defines the grouping, by using special escape sequences such as\ 1,\ 2, and so on
Var sToMatch = "dogdog"; var reDogdog = / (dog)\ 1 dogdog/ alert; / / equivalent to / dogdog/ alert (reDogdog.test (sToMatch)); / / true
Third, backreferences can be used in the replace () method of the String object by using special character sequences such as $1, $2, etc.
Var sToChange = "1234 5678"; var reMatch = / (\ d {4}) (\ d {4}) /; alert (sToChange.replace (reMatch, "$2 $1")); / / "5678 1234"
Candidate for complex patterns: use the pipe character (|) to place between two separate modes
Var reBadWords = / badword | anotherbadword/gi; var sUserInput = "This is a String using badword1 and badword2."; var sFinalText = sUserInput.replace (reBadWords, function (sMatch) {return sMatch.replace (/. / g, "*"); / / replace every letter in a sensitive word with an asterisk})
Non-capture grouping of complex patterns: no backreferences are created compared to captive grouping, storing reverse references slows matching in longer regular expressions, and by using non-captive grouping, you can still have the same capabilities as matching string sequences without the overhead of storing results
Var sToMatch = "# 123456789"; var reNumbers = / # (?:\ d +) /; / / you only need to add a question mark and a colon after the left parenthesis to create a non-capture packet reNumbers.test (sToMatch); alert (RegExp.$1); / / "". The empty string is output because the packet is a non-capture alert (sToMatch.replace (reNumbers, "abcd$1")) / / the output result is "abcd$1" instead of "abcd123456789". No backreferences can be used.
Another example is:
String.prototype.stripHTML = function () {var reTag = / / g; / / matches all HTML tags to prevent the insertion of malicious HTML code return this.replace (reTag, ");}
Complex pattern foresight: tells the regular expression operator to look forward to some characters without moving their position, there is positive foresight (check whether a particular character set appears next) and negative foresight (check the next specific character set that should not appear)
Looking forward (? = n) matches any string that immediately follows the specified string n but does not include n, note that the parentheses here are not grouped
Negative forward-looking (?! n) matches any string that is not immediately followed by the specified string n, such as:
Var sToMatch2 = "bedroom"; var sToMatch3 = "bedding"; var reBed1 = / (bed (? = room)) /; var reBed2 = / (bed (?! room)) /; alert (reBed1.test (sToMatch2)); / / true alert (RegExt.$1); / / output "bed" instead of "bedroom" alert (reBed1.test (sToMatch3)); / / false alert (reBed2.test (sToMatch2)); / / false alert (reBed2.test (sToMatch3)); / / true alert (RegExt.$1) / / the output is also "bed"
Boundaries of complex patterns: used to represent the location of patterns in regular expressions
N $matches any string that ends with n, such as: / (\ w +)\. $/ match the line ending word "one.", "two." Etc.
^ n matches any string that starts with n, such as: / ^ (. +?)\ b / one or more word characters after matching the starting position
\ b find a match at the beginning or end of a word, such as: /\ b (\ Shop?)\ bAccord g or / (\ w+) / g match to extract a word from a string
\ B find matches that are not at the beginning or end of the word
Multi-line mode of complex pattern:
Var sToMatch = "First second\ nthird fourth\ nfifth sixth"; var reLastWordOnLine = / (\ w +) $/ gm; alert (sToMatch.match (reLastWordOnLine)); / / output ["second", "fourth", "sixth"] instead of just "sixth"
Properties and methods of the RegExp object:
Whether the global / / RegExp object has a flag g
Whether the ignoreCase / / RegExp object has a flag I
Whether the multiline / / RegExp object has a flag m
Source text of source / / regular expression
LastIndex / / an integer indicating the character position from which the next match will begin (only filled in when using the exec () and test () functions, otherwise 0)
What is really used is lastIndex, such as:
Var sToMatch = "bbq is short for barbecue"; var reB = / bgamg; reB.exec (sToMatch); alert (reB.lastIndex); / / 1, matching position is 0 Last Index is 1 reB.exec (sToMatch); alert (reB.lastIndex); / / 2 reB.exec (sToMatch); alert (reB.lastIndex); / / 18 reB.lastIndex = 0; / / start matching reB.exec (sToMatch); alert (reB.lastIndex); / / 1 instead of 21
Static attribute
Input, with the short name $_, is finally used for the matching string (the string passed to exec () or test ())
LeftContext, whose short name is $^, the substring before the last match
RightContext, whose short name is $^, the substring after the last match
LastMatch, whose short name is $&, and the last matching character
LastParen, whose short name is $+, and the last matching packet.
Multiline, short name $*, is used to specify whether all expressions use the Boolean value of the multiline pattern. Unlike other properties, it does not depend on the last match executed, it can set the m option of all regular expressions, RegExp.multiline = "true"; note that IE and Opera do not run it.
Var sToMatch = "this has been a short, short summer"; var reShort = / (s) hort/g; reShort.test (sToMatch); alert (RegExg.input); / / "this has been a short, short summer"; alert (RegExg.leftContext); / / "this has been a"; alert (RegExg.rightContext); / / ", short summer"; alert (RegExg.lastMatch); / / "short" alert (RegExg.lastParen) / / "s" compile () / / compiles the regular expression alert (reCat.exec ("a cat, a Cat, a cAt caT"); / / returns an array where the first entry in the array is the first match, and the rest is a reverse reference to alert (reCat.test ("cat")); / / true, which retrieves the specified value in the string and returns true or false.
Methods of String objects that support regular expressions
Var sToMatch = "a bat, a Cat, a fAt, a faT cat"; var reAt = / at/gi; alert (sToMatch.match (reAt)); / / returns an array of all matches contained in the string alert (sToMatch.search (reAt)); / / outputs the position 3 that first appears in the string, and global match g does not work when search () alert (sToMatch.replace (reAt, "Dog")) / replace the substring alert that matches the regular expression (sToMatch.replace (reAt, function (sMatch) {return "Dog";}); alert (sToMatch.split (/\, /)); / / split the string into an array of strings
Common mode
Date: / (?: 0 [1-9] | [12] [0-9] | 3 [01])\ / (?: 0 [1-9] | 1 [0-2])\ / (?: 19 | 20\ d {2}) /
URL:/ ^ http://([w-]+.)+[w-]+(/[w-./?%&=]*)?$/
E-mail address: / ^ (?:\ w +\.?) *\ w + @ (?:\ w +\.?) *\ w.
Domestic telephone number: d {3}-d {8} | d {4}-d {7}
Tencent QQ number: [1-9] [0-9] {4,}
Zip code: [1-9] d {5} (?! d)
ID: d {15} | d {18}
Ip address: dong.d+
Chinese character: [u4e00-u9fa5]
Double-byte characters (including Chinese characters): [^ x00-xff]
String.prototype.len=function () {return this.replace ([^ x00-xff] / g, "aa") .length;}
Full-width character: / [^ uFF00-uFFFF] / g
Match specific numbers:
^ [1-9]\ dmatching $/ / matching positive integers ^-[1-9]\ dmatching $/ / matching negative integers ^ -? [1-9]\ dmatching $/ / matching integers ^ [1-9]\ d* | 0 $/ / matching non-negative integers (positive integers + 0) ^-[1-9]\ d* | 0 $/ matching non-positive integers (negative integers + 0) ^ [ 1-9]\ d*\.\ d* | 0.\ d* [1-9]\ dfloat $/ / match positive floating point number ^-([1-9]\ d*\.\ d* | 0\.\ d* [1-9]\ d*) $/ match negative floating point number ^ -? ([1-9]\ d*\.\ d* | 0.\ d* [1-9]\ d* | 0?\ .0 + | 0) $ / / match floating point numbers ^ [1-9]\ d *.\ d * | 0.\ d * [1-9]\ d * | 0?\ .0 + | 0 $/ / match non-negative floating point numbers (positive floating point numbers + 0) ^ (- ([1-9]\ d *\.\ d * | 0\.\ d* [1-9]\ d*)) | 0?\ .0 + | 0 $/ match non-positive floating point numbers (negative floating point + 0)
Is not very comprehensive, very detailed, feel good on the good collection of this article, js regular expression is a very important learning link, we must study hard.
At this point, the study of "js regular expression summary" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.