First, what is a regular expression
Regular expressions, also known as regular expressions. (English: Regular Expression, often abbreviated in code as regex, RegExp, or re), a concept of computer science. Regular tables are often used to retrieve and replace text that conforms to a pattern (rule).
Many programming languages support the use of regular expressions for string manipulation. For example, in Perl, a powerful regular expression engine is built in. The concept of regular expressions was initially popularized by tool software (such as SED and grep) in Uinx. Regular expressions are usually abbreviated as "regex", singular with regexp, regex, plural regexps, regexes, Regexen.
* representative of multiple ? Represents a character (can have, can be none)
--The book number is either 5 digits or 5 digits plus-4 digits, such as 12345 or 12345-0001
\D{5} (-\d{4})?--ABC? Match who? ABC, ab--A (BC) matches who ABC, BC//BC is a sub-match * * Sub-matching circle spread out the expression part is a sub-match (also known as a sub-expression), in addition to the results of the entire expression matching can be obtained, you can also get the sub-expression matching results. Using the Verification tool, on a (BC)? To verify, enter ABC, get the result)//? Specify the previous 0 or 1 positions 0:abc position 1:BC The original content of multiple subexpression matches is stored in the buffer in the order in which they appear from left to right in the regular expression pattern, a process known as capture, where the sub-match in the circle extension can be captured in the entire expression. After the place is referenced, the first round expansion number (that is, the first sub-match) captures the content with \1, the second with \2, and so on-match two consecutive identical numbers, the \d \1--match 5 consecutive same numeric characters 66666 (\d) \1{4}--match 1221, 4664, 7887, 0220 such//(\d) (\d) \2\1--match 1225, 4668, 5887 such (unlike the previous example, this is not the same)//\d (\d) \1\ DIi. RegExp objects in JavaScriptEach regular expression pattern corresponds to one RegExp, JavaScript, and there are two ways to create a REGEXP instance. --Using the RegExp object new RegExp ("pattern" [, "Flags"])--Using the RegExp object's implicit constructor/patern/[flags] Var reg=/^\d{8}$/NOTE: The Flags flag character -G is used as the global flag//For all matches in the text, otherwise the oldest-I is used as the ignore case-m as a multiline flag when creating a RegExp instance object using the display constructor, each \ in the original regular expression pattern text should be replaced with \ \, for example, the following two statements is equivalent to
var r =New RegExp ("\\d{5}"); What if I use to match? to use a \\\\ (four) var r=/\d{5}/;
The method of the ==regexp object--Test (STR) contains--exec (str) searches for a string, returns an array, and does not find the method that returns null--compile ==string objects related to regular expressions--match syntax format Match (REGEXP), similar to the Exec method of the RegExp object, returns an array. Note that the argument passed to it is a RegExp object, and if the global flag is set, the returned array contents and the return of the regexp.exec () are different. The returned array is a complete match, not the first one is the complete match, and the other is the sub-match result--search syntax for search (REGEXP) returns the position of the first matched string--replacereplace ( Regexp,replacetext)--split (REGEXP)Third, regular expression syntaxTo run regular expressions flexibly, it is necessary to understand the functions of the meta characters, which are functionally divided into: 1. Qualifier 2. Select the match 3. Grouping combinations and reverse references 4. special characters 5. Character match 6. Locator = = Qualifier 1) {n} required to appear in front of n //\d{5}, a{5}2) {n,} prescribes at least n times in front of // Note that the word "at least" 3) {N,m} Specifies the number of occurrences between N and M//note, do not add spaces (N&NB Sp And m are included) 4) + Specifies that the first occurrence of the first character or the expanded number must be one time, or multiple//\d+ -9 or 4567zo+ mismatch z matching zo, matching zoo  ; equivalent to zo{1,}5) * Can be any time zo* match Z, matching zo, matching zoooo equivalent to zo{0,}6)? Previous content once or 0 times zo? matches Z, matches Zo, does not match zoo, is equivalent to zo{0,1}== selection match | , choose one, try to get cat|dog nice, matching the cat and dog nice attached: (cat|dog) nice == grouping combination and inverse reference grouping combination: a symbol that combines a part of a regular expression with a reverse reference character: The identification symbol used to match what was captured by the previous grouping combination 1) (pattern) Note to match the literal meaning (, to use \ (2) \num This is the reverse reference that matches the contents of the specific buffer specified by num such as to match 5 consecutive identical numbers Character to be used (\d) \1{4}3) {?:p attern} does not use the pattern part as a sub-match, mainly for situations where a combination of rows must be made, but does not want the grouped parts to be sub-matched, save buffers such as this is (a cat) written in this I S (?: a cat) 4) (? =pattern) forward lookahead match for example: Windows (? =nt|2000), Windows only in Windows 2000 or Windows NT matches instead of win in Windows 2003 Dows Match, noteIt matches the results of just the Windows section. For example, a common application: The full-text Windows 2000 or Windows NT front windows rewrite to win, this way to replace (/^windows (=nt|2000) $/, "Win"); Note: Windows (? =nt| cat , what is the matching result in the text My Windows NT Cat, and what does not match, because it matches the window CAT5) (?!). pattern) Reverse Prediction first match = = Special Word regular the expression, with the backslash \ back tight root other escape character sequence to represent the original character 1 \xn (here n must be two bits) \x41 matching character a \x04 The meaning is that \x04 the character that is given by the string to be followed by a tight root character of N is a 1-bit 8 binary number 3 \nm mn is a one-bit 8 over 4 \nml n is 0-3 binary number 8 \un match Unicode code equals n characters, such as \u00a9 Match the copyright number 6 \cx For example \cm matches the control character represented by the Control+m, which is the carriage return 7 \f match the page break equivalent to \x0a and \CJ8 \ n Match carriage return equivalent to \x0d and \CM9 \ Match tab equivalent to \x09 and \CL10 \v matching vertical tab, such as == character match 1) [...] match any one of the characters contained therein [ABC] matches any one of the a,b,c, note that if you want to include [to put it in First bit, if you want to include \ to write \\2) [^ ...] In contrast to the above, the match does not appear for any character example [^ABC] as long as it is not a, or B, or C on the line note that ^ must be placed in front, otherwise it is literally ^3) [A-z] matches the specified pan-circumference for example [ 0-9] = \d4) [^a-z] matches any character not A-Z 5) \d any numeric character is equivalent to [0-9]6] \d \d inverse operation equivalent to [^0-9] //inverse operation is uppercase 7) \s matches any of theWhite space Character (space) 8) \s is \s inverse 9) \w equivalent [a-za-z0-9_] any uppercase and lowercase letters, numbers, underscores//Note it does not match-but matches _10)/w is \w equivalent to [inverse]. Match any character except \ n, to match itself, with \.
var setr= "Gaorui said:" I am. Play chess.... It's very .... Bad "; // For the first time, remove all. Str=str.replace (/\./g, ""); // The second time, remove the duplicate word str=str.replace (/(.) \1/g, "$"); // Result: Gaorui said: I play chess very much
= = Locator
1) ^ The specified match must occur at the beginning of the target string and must be present at the top of the page to be useful
For example, ^o matches the o in OK, but the O mismatch in dog, if the RegExp object instance is set
The MultiLine property, ^ also matches the first line, which matches the position after \ n or \ r
2) $ matches the end position of the target string, must appear at the end of the role of the locator
For example, o$ matches the O in Hello, but does not match the O in OK
3) \b matches the boundary of a word (that is, a word), it contains the position between the word and the space, and the beginning and end of the target string.
For example "er\b" matches er in never OK, but does not match er in Verx
"\bis\b" matches the IS in Anicecat Isisisdog
4) \b \b Inverse operation, the result is opposite to the previous example
Example
Call replace (/win/g, "close") to replace win a window, get close a Closedow
Call Repalce (/\bwin\b, "close"/) to get close a window
Example
If you want to add the same markup text to each line in the contents of a piece of text, just use this markup text to
^ Do a global replacement
var str= "AAA\NBBB\NCCC";
Alert (Str.replace (/^/MG, "#")); The m here means a lot of lines.
Results:
#aaa
#bbb
#ccc
= = Attached
----literal characters
Some metacharacters do not represent its original literal meaning, and if you want to match their literal meaning, you must use the
\ Escape
The character that needs to be escaped $ (*. [ ? \ / ^ { |
----priority order
* higher than the character priority, such as ab* is a combination of B and *, and a combination of the previous
() higher than * priority, (AB) * is a and b combination, then and * combination, Word transmitting | High priority,
A|BC is a combination of BC, then and a
Some examples of regular expression patterns
Match Blank line/^\s*$/
Match HTML tag/< (\s+) (\s[^>]*)? >[\s\s]*<\/\1\s*>/
Match email/^[a-za-z0-9_-][email protected][a-za-z0-9_-]+ (\.[ a-za-z0-9_-]+) +$/
Match two identical adjacent words/\b ([a-z]+) \1\b///For example Catcat
Match IP address/^\d{1,2}|1\d\d|2[0-4]\d|25[0-5] (\. ( \D{1,2}|1\D\D|2[0-4]\D|25[0-5])) {3}$/
\u4e00-\u9fa5 Chinese
Iv. using regular expression validation in Java
//Example One verification hand number Public Static BooleanCheckphone (String str) {Booleanresult=true; if(Str.length ()!=11) {result=false; System.out.println ("Incorrect number Length"); } if(!str.startswith ("1") {result=false; System.out.println ("Not starting with 1."); } Char[] arr=Str.tochararray (); for(inti=0;i<arr.length;i++){ if(! (arr[i]>= ' 0 ' &&arr[i]<= ' 9 ') {result=false; System.out.println ("Contains illegal characters"); Break; } } returnresult; }
//Example Two Public Static BooleancheckPhone2 (String str) {Booleanresult=true; Try{long.parselong (str); } Catch(Exception ex) {System.out.println ("Phone number format is incorrect"); Result=false; } returnresult; }
// public static boolean CheckPhone3 (string str) {string regex = "1[3584]\\d{9}" ; return str.matches (regex); }
// public static void Span style= "COLOR: #000000" > SplitDemo1 () {String str = "AAA---BBB-------CCC----DDD" ; String [] strlist =str.split ("-+" for (String s:strlist) {SYSTEM.OUT.P Rintln (s); } }
// Public static void SplitDemo2 () {String str =" aaa.bbb.ccc.ddd " =str.split ("\ \.") for (String s:strlist) {System.out.print ln (s); } }
// Public static void SplitDemo3 () {String str =" c:\\windows\\system32\\aa.bmp " =str.split ("\\\\" for (String s:strlist) {System.out.print ln (s); } }
// example seven replace public static void Replacedemo () {String str = "To 1234 want to do 456 fake card, please contact 13503688749 or 13302564798 or 1505002 0120 or 257 "; String regex = "\\d{11}" ; System.out.println (Str.replaceall (regex, "Mash"
// Example VIII get Public Static void Getdemo () { String str= "Lin Hua Xie Spring red big lush, too hurriedly, good big green onion big lush green onion lush"; String regex= "Large Lush +"; Pattern pattern=pattern.compile (regex); Matcher Matcher=pattern.matcher (str); while (Matcher.find ()) { System.out.println (Matcher.group ()); } }
//example nine gets from the Web page Public Static voidWebgetdemo ()throwsException {URL url=NewURL ("http://localhost:8080/book-shop/login.jsp"); URLConnection Conn=url.openconnection (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (Conn.getinputstream ())); String Regex= "[A-za-z0-9_-][email protected][a-za-z0-9_-]+ (\\.[ a-za-z0-9_-]+) + "; Pattern Pattern=pattern.compile (regex); String Str=NULL; while((Str=br.readline ())! =NULL) {Matcher Matcher=Pattern.matcher (str); while(Matcher.find ()) {System.out.println (Matcher.group ()); } } }
Java Basics-Regular expressions