Basic usage of regular expressions in Java

Source: Internet
Author: User

A regular expression is a specification that can be used for pattern matching and substitution, and a regular expression is a text pattern consisting of ordinary characters (such as characters A through Z) and special characters (metacharacters), which describe one or more strings to match when looking for a text body. A regular expression, as a template, matches a character pattern to the string you are searching for.

As we all know, in the process of development, it is inevitable to encounter the need to match, find, replace, judge the occurrence of strings, and these circumstances are sometimes more complex, if the pure coding method, often waste the programmer's time and energy. Therefore, learning and using regular expressions has become the main means to solve this contradiction.

As you all know, regular expressions are a specification that can be used for pattern matching and substitution, and a regular expression is a text pattern consisting of ordinary characters (such as characters A through Z) and special characters (metacharacters), which describe one or more strings to match when looking for a text body. A regular expression, as a template, matches a character pattern to the string you are searching for.

Since jdk1.4 launched the Java.util.regex package, we have provided a good Java regular Expression application platform.

Because the regular expression is a very complex system, so I just cite some of the concepts of entry, more please refer to the relevant books and self-exploration.

* The following are common syntax for normal expressions in Java:

The value range of the character
1.[ABC]: Indicates that you canIt could be A, B, or C.
2.[^ABC]: Indicates that it is not any one of the A,b,c
3.[a-za-z]: denotes the English alphabet
4.[0-9]: Indicates a number

A concise character representation
.: Matches any character
\d: Indicates a number
\d: Indicates non-numeric
\s: Represented by a null character, [\t\n\r\x\f]
\s: represented by non-null characters, [^\s]
\w: denotes letters, numbers, underscores, [a-za-z0-9_]
\w: Indicates that it is not made up of letters, numbers, underscores

Quantity expression
1.: indicates 0 or 1 occurrences
2.+: Indicates 1 or more occurrences
3.*: Indicates 0, 1, or more occurrences
4.{n}: Indicates the occurrence of n times
5.{n,m}: Indicates n~m times occurred
6.{n,}: Indicates the occurrence of n or n times

Logical Expressions
1.XY: Represents x followed by y, where x and Y are part of the regular expression, respectively
2.x| Y: denotes x or y, for example "Food|f" matches foo (d or F), while "(food) |f" matches food or F
3. (x): Sub-expression, consider X as a whole

Two classes are available in Java to support the operation of a regular expression
The pattern class and the Matcher class, respectively, under Java.util.regex.
Use the pattern class to split a string, using the method string[] Split (charsequence input)
Use the Matcher class for validation and substitution of strings,
The method used for matching is Boolean matches ()
The substitution method is string ReplaceAll (string replacement)

The method of constructing the pattern class is private
So we use the Pattern p = pattern.compile ("A*b");
The instantiation of the Matcher class relies on the object of the pattern class matcher m = P.matcher ("Aaaaab");

In practical development, we seldom use the pattern class or the Matcher class directly for convenience, but instead use the method under the String class
Validation: Boolean matches (String regex)
Split: string[] Split (String regex)
Replacement: String ReplaceAll (String regex, string replacement)

The following is a simple use of regular expressions:
1. Test01.java: Use regular expressions to make your code very concise.
1  PackageTest_regex;2  Public classTest01 {3      Public Static voidMain (string[] args) {4String str = "1234567";5 //char[] C = Str.tochararray ();6 //Boolean B = true;7 //For (char c1:c) {8 //if (! ( c1>= ' 0 ' &&c1<= ' 9 ')) {9 //B = false;Ten //Break ; One //            } A //        } - //System.out.println (b); -  theString regex = "\\d+"; - System.out.println (Str.matches (regex)); -     } -}

2, Testmatcher01.java (use of the Matcher class, for string validation)

1  PackageTest_regex;2 ImportJava.util.regex.Pattern;3 ImportJava.util.regex.Matcher;4  Public classTestMatcher01 {5      Public Static voidMain (string[] args) {6String str = "1234567ABC";7String regex = "\\w{10,}";8 //Pattern Pat = pattern.compile (regex);9 //Matcher mat = Pat.matcher (str);Ten //System.out.println (Mat.matches ()); One System.out.println (Str.matches (regex)); A     } -}

3, Testmatcher02.java (use of the Matcher class, for string substitution)

1  PackageTest_regex;2 ImportJava.util.regex.Pattern;3 ImportJava.util.regex.Matcher;4  Public classTestMatcher02 {5      Public Static voidMain (string[] args) {6String str = "12y34h56dad7";7String regex = "[a-za-z]+";8 //Pattern Pat = pattern.compile (regex);9 //Matcher mat = Pat.matcher (str);Ten //System.out.println (Mat.replaceall (":")); OneSystem.out.println (Str.replaceall (Regex, "-")); A     } -}

4, Testpattern01.java (use of the pattern class, used for splitting the string)

1  PackageTest_regex;2 ImportJava.util.regex.Pattern;3  Public classTestPattern01 {4      Public Static voidMain (string[] args) {5String str = "tom:30| jerry:20| Bob:25 ";6String regex = "\\|";7 //Pattern Pat = pattern.compile (regex);8 //string[] arr = pat.split (str);9string[] arr =str.split (regex);Ten          for(String s:arr) { One System.out.println (s); A         } -     } -}

5, Testregex01.java (probably determine whether an e-mail address is legitimate)

1  PackageTest_regex;2  Public classTestRegex01 {3     //determine if an email address is legitimate4      Public Static voidMain (string[] args) {5         //the suffix of the default mailbox here is. com or. net.cn6String str = "[Email protected]";7String regex = "\\[email protected]\\w+\\. (com|net.cn) ";8 System.out.println (Str.matches (regex));9     }Ten}

Basic usage of regular expressions in Java

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.