Java basics --- Regular Expressions and basic Regular Expressions

Source: Internet
Author: User

Java basics --- Regular Expressions and basic Regular Expressions

Regular Expressions are supported in many languages, such as Perl, PHP, Python, JavaScript, and JScript. Some text editors use regular expressions to implement advanced search-replace functions.

A regular expression is a regular expression that can be used for pattern matching and replacement. a regular expression consists of common characters (such as characters a to z) and special characters (metacharacters) it is used to describe one or more strings to be matched when the text subject is searched. A regular expression is used as a template to match a character pattern with the searched string.

In this article, we will only introduce the basic regular expressions. If you want to learn more, you can find your own materials!

Regular Expressions are introduced to java after JDK1.4. JDK is the earliest version. To use regular expressions, you need to add a regular expression Development Kit provided by Apache.

Pattern, Matcher class

To apply a regular expression in a program, you must rely on the Pattern class and Matcher class, which are both defined in the Java. util. regex package. Pattern is mainly used to compile regular expressions. Matcher is used to verify whether a string complies with the regular expression.

How many small programs can be used to check whether the regular expression is a number?
Package com. regular Expression; import java. util. regex. pattern; public class RegexDemo02 {public static void main (String args []) {String str = "1234567890"; // This String consists of numbers if (Pattern. compile ("[0-9] + "). matcher (str ). matches () {// use regular System. out. println ("is composed of numbers! ");} Else {System. out. println (" is not composed of numbers! ");}}};

Print result: it is composed of numbers!

Date check?
Package com. regular Expression; import java. util. regex. pattern; import java. util. regex. matcher; public class RegexDemo03 {public static void main (String args []) {String str = "1983-07-27 "; // specify a date format String pat = "\ d {4}-\ d {2}-\ d {2 }"; // specify the Regular Expression Pattern p = Pattern. compile (pat); // instantiate the Pattern class Matcher m = p. matcher (str); // instantiate the Matcher class if (m. matches () {// verify the match, using the regular System. out. println ("the date format is valid! ");} Else {System. out. println (" the date format is invalid! ");}}};

Printed result: the date format is valid!

Split string
Package com. regular Expression; import java. util. regex. pattern; import java. util. regex. matcher; public class RegexDemo04 {public static void main (String args []) {// retrieve the characters in the String, that is, split String str = "A1B22C333D4444E55555F" according to the number "; // specify a String pat = "\ d +"; // specify the Regular Expression Pattern p = Pattern. compile (pat); // instantiate the Pattern class String s [] = p. split (str); // perform the split operation for (int x = 0; x <s. length; x ++) {System. out. print (s [x] + "\ t ");}}};

Print results

Replace string
Package com. regular Expression; import java. util. regex. pattern; import java. util. regex. matcher; public class RegexDemo05 {public static void main (String args []) {// retrieve the characters in the String, that is, split String str = "A1B22C333D4444E55555F" according to the number "; // specify a String pat = "\ d +"; // specify the Regular Expression Pattern p = Pattern. compile (pat); // instantiate the Pattern class Matcher m = p. matcher (str); // instantiate the object String newString = m. replaceAll ("_"); System. out. println (newString );}};

Print results

Regular Expressions can be used to easily verify, split, replace, and perform escape operations on Ming characters. Matcher and Pattern classes are rarely used in actual development, directly use the regular expression support provided by the String class. Regular rules
Character Description
\ Mark the next character as a special character, a literal character, or a backward reference, or an octal escape character. For example,n"Matching characters"n". "\n"Match a line break. Serial"\\"Match"\"And"\("Match"(".
^ Matches the start position of the input string. If the Multiline attribute of the RegExp object is set, ^ matches"\n"Or"\r.
$ Matches the end position of the input string. If the Multiline attribute of the RegExp object is set, $ also matches"\n"Or"\r"Previous location.
* Matches the previous subexpression zero or multiple times. For example, zo * can match"z"And"zoo". * Is equivalent to {0 ,}.
+ Match the previous subexpression once or multiple times. For example,zo+"Matching"zo"And"zoo", But cannot match"z". + Is equivalent to {1 ,}.
? Match the previous subexpression zero or once. For example,do(es)?"Matching"does"Or"does"In"do".? It is equivalent to {0, 1 }.
{N} N is a non-negative integer. Match n times. For example,o{2}"Cannot match"Bob"In"o", But can match"food.
{N ,} N is a non-negative integer. Match at least n times. For example,o{2,}"Cannot match"Bob"In"o", But can match"foooood. "o{1,}"Equivalent"o+". "o{0,}"Is equivalent"o*".
{N, m} Both m and n are non-negative integers, where n <= m. Match at least n times and at most m times. For example,o{1,3}"Match"fooooood. "o{0,1}"Equivalent"o?". Note that there must be no space between a comma and two numbers.
? When this character is followed by any other delimiter (*, + ,?, The matching mode after {n}, {n ,}, {n, m}) is not greedy. The non-Greedy mode matches as few searched strings as possible, while the default greedy mode matches as many searched strings as possible. For example,oooo","o+?"Will match a single"o", And"o+"Will match all"o".
. Match the\n. To match include"\n"Use any character, such"(.|\n).
(Pattern) Match pattern and obtain this match. The obtained match can be obtained from the generated Matches set. The SubMatches set is used in VBScript, and $0… is used in JScript... $9 attribute. To match the parentheses, use the"\("Or"\)".
(? : Pattern) Matches pattern but does not get the matching result. That is to say, this is a non-get match and is not stored for future use. This is in use or the character"(|)It is very useful to combine all parts of a mode. For example"industr(?:y|ies)"Is a ratio"industry|industries"A simpler expression.
(? = Pattern) Forward validation pre-query: matches the search string at the beginning of any string that matches pattern. This is a non-get match, that is, the match does not need to be obtained for future use. For example,Windows(?=95|98|NT|2000)"Matching"Windows2000"In"Windows", But cannot match"Windows3.1"In"Windows". Pre-query does not consume characters, that is, after a match occurs, the next matching search starts immediately after the last match, instead of starting after the pre-query characters.
(?! Pattern) Forward negative pre-query: matches the search string at the beginning of any string that does not match pattern. This is a non-get match, that is, the match does not need to be obtained for future use. For example,Windows(?!95|98|NT|2000)"Matching"Windows3.1"In"Windows", But cannot match"Windows2000"In"Windows". Pre-query does not consume characters. That is to say, after a match occurs, the next matching search starts immediately after the last match, instead of starting after the pre-query characters.
(? <= Pattern) The reverse direction is certainly precheck, which is similar to the forward positive direction. For example,(?<=95|98|NT|2000)Windows"Matching"2000Windows"In"Windows", But cannot match"3.1Windows"In"Windows".
(? <! Pattern) Reverse negative pre-query, similar to forward negative pre-query, is in the opposite direction. For example,(?<!95|98|NT|2000)Windows"Matching"3.1Windows"In"Windows", But cannot match"2000Windows"In"Windows".
X | y Match x or y. For example,z|food"Matching"z"Or"food". "(z|f)ood"Match"zood"Or"food".
[Xyz] Character Set combination. Match any character in it. For example,[abc]"Matching"plain"In"a".
[^ Xyz] Negative value character set combination. Match any character not included. For example,[^abc]"Matching"plain"In"p".
[A-z] Character range. Matches any character in the specified range. For example,[a-z]"Matching"a""z"Any lowercase letter in the range.
[^ A-z] Negative character range. Matches any character that is not within the specified range. For example,[^a-z]"Can match any"a""z"Any character in the range.
\ B Match A Word boundary, that is, the position between a word and a space. For example,er\b"Matching"never"In"er", But cannot match"verb"In"er".
\ B Match non-word boundary. "er\B"Matching"verb"In"er", But cannot match"never"In"er".
\ Cx Match the control characters specified by x. For example, \ cM matches a Control-M or carriage return character. The value of x must be either a A-Z or a-z. Otherwise, c is regarded as an original"c"Character.
\ D Match a numeric character. It is equivalent to [0-9].
\ D Match a non-numeric character. It is equivalent to [^ 0-9].
\ F Match a form feed. It is equivalent to \ x0c and \ cL.
\ N Match A linefeed. It is equivalent to \ x0a and \ cJ.
\ R Match a carriage return. It is equivalent to \ x0d and \ cM.
\ S Matches any blank characters, including spaces, tabs, and page breaks. It is equivalent to [\ f \ n \ r \ t \ v].
\ S Match any non-blank characters. It is equivalent to [^ \ f \ n \ r \ t \ v].
\ T Match a tab. It is equivalent to \ x09 and \ cI.
\ V Match a vertical tab. It is equivalent to \ x0b and \ cK.
\ W Match any word characters that contain underscores. It is equivalent to[A-Za-z0-9_]".
\ W Match any non-word characters. It is equivalent to[^A-Za-z0-9_]".
\ Xn Match n, where n is the hexadecimal escape value. The hexadecimal escape value must be determined by the length of two numbers. For example,\x41"Match"A". "\x041"Is equivalent"\x04&1". The regular expression can use ASCII encoding ..
\ Num Matches num, where num is a positive integer. References to the obtained matching. For example,(.)\1"Matches two consecutive identical characters.
\ N Identifies an octal escape value or a backward reference. If at least n subexpressions are obtained before \ n, n is backward referenced. Otherwise, if n is an octal digit (0-7), n is an octal escape value.
\ Nm Identifies an octal escape value or a backward reference. If at least one child expression is obtained before \ nm, the nm is backward referenced. If at least n records are obtained before \ nm, n is a backward reference followed by text m. If none of the preceding conditions are met, if n and m are Octal numbers (0-7), \ nm matches the octal escape value nm.
\ Nml If n is an octal number (0-3) and m and l are Octal numbers (0-7), the octal escape value nml is matched.
\ Un Match n, where n is a Unicode character represented by four hexadecimal numbers. For example, \ u00A9 matches the copyright symbol (©).
Common Regular Expressions
User Name /^ [A-z0-9 _-] {} $/
Password /^ [A-z0-9 _-] {6, 18} $/
Password 2 (? = ^. {8 ,}$ )(? =. * \ D )(? =. * \ W + )(? =. * [A-Z]) (? =. * [A-z]) (?!. * \ N). * $ (consisting of numbers, uppercase letters, lowercase letters, and punctuation marks. Each of the four must have more than 8 digits)
Hexadecimal value /^ #? ([A-f0-9] {6} | [a-f0-9] {3}) $/
Email /^ ([A-z0-9 _\. -] +) @ ([\ da-z \. -] + )\. ([a-z \.] {2, 6}) $/
/^ [A-z \ d] + (\. [a-z \ d] +) * @ ([\ da-z] (-[\ da-z])?) + (\. {1, 2} [a-z] +) + $/or \ w + ([-+.] \ w +) * @ \ w + ([-.] \ w + )*\. \ w + ([-.] \ w + )*
URL /^ (Https? :\/\/)? ([\ Da-z \. -] + )\. ([a-z \.] {2, 6}) ([\/\ w \. -] *) * \/? $/Or [a-zA-z] +: // [^ \ s] *
IP address /(2 [0-4] \ d | 25 [0-5] | [01]? \ D ?) \.) {3} (2 [0-4] \ d | 25 [0-5] | [01]? \ D ?) /
/^ (? :(? : 25 [0-5] | 2 [0-4] [0-9] | [01]? [0-9] [0-9]?) \.) {3 }(? : 25 [0-5] | 2 [0-4] [0-9] | [01]? [0-9] [0-9]?) $/Or (2 [0-4] \ d | 25 [0-5] | [01]? \ D ?) \.) {3} (2 [0-4] \ d | 25 [0-5] | [01]? \ D ?)
HTML Tag /^ <([A-z] +) ([^ <] + )*(? :> (. *) <\/\ 1> | \ s + \/>) $/or <(. *)(. *)>. * <\/\ 1> | <(. *) \/>
Delete Code \ comments (? <! Http: | \ S) //. * $
Match double-byte characters (including Chinese characters) [^ \ X00-\ xff]
Chinese characters (characters) [\ U4e00-\ u9fa5]
Range of Chinese Characters in Unicode encoding /^ [\ U2E80-\ u9FFF] + $/
Chinese and fullwidth punctuation marks (characters) [\ U3000-\ u301e \ ufe10-\ ufe19 \ ufe30-\ ufe44 \ ufe50-\ ufe6b \ uff01-\ uffee]
Date (year-month-day) (\ D {4} | \ d {2})-(0? ([1-9]) | (1 [1 | 2])-(0? [1-9]) | ([12] ([1-9]) | (3 [0 | 1])
Date (month/day/year) (0? [1-9] {1}) | (1 [1 | 2])/(0? [1-9] | ([12] [1-9]) | (3 [0 | 1])/(\ d {4} | \ d {2 })
Time (hour: minute, in 24-hour format) (1 | 0 ?) [0-9] | 2 [0-3]) :( [0-5] [0-9])
Chinese mainland fixed phone number (\ D {4}-| \ d {3 }-)? (\ D {8} | \ d {7 })
Mobile phone number in Mainland China 1 \ d {10}
China mainland zip code [1-9] \ d {5}
ID No. of Mainland China (15 or 18 digits) \ D {15} (\ d [0-9xX])?
Non-negative integer (positive integer or zero) \ D +
Positive Integer [0-9] * [1-9] [0-9] *
Negative integer -[0-9] * [1-9] [0-9] *
Integer -? \ D +
Decimal (-? \ D +) (\. \ d + )?
Blank line \ N \ s * \ r or \ n (editplus) or ^ [\ s \ S] * \ n
QQ number [1-9] \ d {4 ,}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.