Basic usage of regular expressions in Java

Source: Internet
Author: User

Https://www.cnblogs.com/xhj123/p/6032683.html

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 may be a, may be B, it may be 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 package Test_regex; 2 public class Test01 {3 public     static void Main (string[] args) {4         String str = "1234567"; 5//        char[] C = St R.tochararray (); 6//        Boolean B = true; 7//For        (char c1:c) {8//            if (! ( c1>= ' 0 ' &&c1<= ' 9 ')) {9//                B = false;10//                break;11//            }12//        }13//        System.out.println (b);         String regex = "\\d+";         System.out.println (Str.matches (regex));     }18}

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

1 package Test_regex; 2 Import Java.util.regex.Pattern; 3 Import Java.util.regex.Matcher;  4 public class TestMatcher01 {5 public     static void Main (string[] args) {6         string str = "1234567ABC"; 7         string Regex = "\\w{10,}"; 8//        Pattern Pat = pattern.compile (regex); 9//        Matcher mat = Pat.matcher (str);//        System.out.println ( Mat.matches ());         System.out.println (Str.matches (regex));     }13}

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

1 package Test_regex; 2 Import Java.util.regex.Pattern; 3 Import Java.util.regex.Matcher; 4 public class TestMatcher02 {5 public     static void Main (string[] args) {6         String str = "12y34h56dad7"; 7         Stri ng regex = "[a-za-z]+"; 8//        Pattern Pat = pattern.compile (regex); 9//        Matcher mat = Pat.matcher (str);//        System.out.println ( Mat.replaceall (":"));         System.out.println (Str.replaceall (Regex, "-"));     }13}

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

1 package Test_regex; 2 Import Java.util.regex.Pattern; 3 public class TestPattern01 {4 public     static void Main (string[] args) {5         String str = "tom:30| jerry:20| Bob:25 "; 6         String regex = "\\|"; 7//        Pattern Pat = pattern.compile (regex); 8//        string[] arr = pat.split (str); 9         S tring[] arr = str.split (regex); Ten for         (String s:arr) {             System.out.println (s);         }13     }14}

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

1 package Test_regex; 2 public class TESTREGEX01 {3     //Determine if an email address is valid 4 public     static void Main (string[] args) {5         //Here The default mailbox suffix is. com or. n et.cn 6         String str = "[email protected]"; 7         string regex = "\\[email protected]\\w+\\." ( com|net.cn) "; 8         System.out.println (str.matches (regex)); 9     }10}

Basic usage of regular expressions in Java (GO)

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.