Java Regular Expressions

Source: Internet
Author: User
Tags character classes ming

package com.fish.regex;/*   Regular expression: a regular expression is a rule used to manipulate strings, regular expression rules use special conformance representations    requirements: test a QQ number  1, can not start with 0  2, length 5-11 3, can only be composed of digital    check mailbox, check * * * number, check the phone number  */  public class  demo1 {    public static void main (String[] args)  {         String qq =  "1234557";         /*if (!qq.startswith ("0")) {        if (qq.length () >=5 && qq.length () <=11) {             try {                 long.parselong (QQ);                 system.out.println ("Congratulations, you got a legit qq");             } catch  (exception e)  {                 // TODO: handle exception        &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Illegal qq,qq numbers can only be made up of numbers");             }             }else {                 system.out.println ("The length of the illegal qq,qq can only be 5~11 bit");             }        }else{             //starting with 0            &NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Illegal qq,qq cannot start with 0");        }*/      &nBsp;  system.out.println (Qq.matches ("[1-9]\\d{4,10}")? " Legal QQ ":" Illegal QQ ");     }}


Package com.fish.regex;public class demo2 {    public static  void main (String[] args)  {                /*         Predefined character Classes           .  any character (may or may not match the line terminator)           \d  Digital:[0-9]         \d  non-digital: [^0-9]          \s  whitespace characters: [ \t\n\x0b\f\r]  \r return  \n   Line break         \S  non-whitespace characters:[^\s]          \w  Word characters: [a-za-z_0-9]         \w   Non-word characters:[^\w]         Note: Any predefined characters can only match one character before they are prefixed with a quantity word          */               system.out.println ("Any character:" + "%". Matches ("."));         system.out.println ("Numeric character:" + "+") matches ("\\d");   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Non-numeric characters:" + "@". Matches ("\\d"));         system.out.println ("White space character:" + "\ R") matches ("\\s");       &NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Non-whitespace character:" + "\ n"). Matches ("\\s");         System.out.println ("Word Character:" + "". Matches ("\\w"));         SYSTEM.OUT.PRINTLN ("Non-word character:" + "@". Matches ("\\w"));                /*        Greedy  Quantity Words           x? x, not once or once           x* x, 0 or more times         x+ x, one or more           x{n} x, exactly  n  times          x{n,}  x, at least  n  times          x{n,m} x, at least  n  times, But not more than  m  times          */                system.out.println ("? Not once or once: "+" 1 ". Matches (" \\d "));         system.out.println ("*  0 or more times:" + "1". Matches ("\\d*"));         system.out.println ("+  appears at least once:" + "1". Matches ("\\d+"));         system.out.println ("{times}  happens n times:" + "12345678901". Matches ("\\d{11 } ");         system.out.println (" {Number of times,}  at least the specified number of occurrences: "+" 12345678901 " . Matches ("\\d{3,}");  &Nbsp;      system.out.println ("{Number of times 1, number of times 2}  specify the range of occurrences:" + "12345". Matches ("\\d{ 3,4} ");               /*          scope Word         [abc] a, b   or  c (simple Class)          [^abc]  any character except  a, b , or  c (negative)          [a-zA-Z] a  to  z  or  a   to  z, the letters at both ends are included (range)          Note: The range word contains no matter how long the content is, No number of words can match only one character.         */       &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("abc". Matches ("[ABC]"));         system.out.println ("@". Matches ("[^ABC]"));         system.out.println ("Characters can appear in A-Z"+" a ". Matches (" [a-za-z#] ");     }} 


package com.fish.regex;import java.util.arrays;/*  regular expressions are mainly used to manipulate strings, and regular expressions have the following applications for string manipulation.   Match:  matches ()   Cut: Split ()   Replace  :replaceall (string regex, string  Replacement)   Find:  */public class demo3 {    public static  void main (String[] args)  {    matchesphone ("1355642459");     matchestel ("020-88524574");     testplit1 ();     testplit2 () ;      replacetest1 ()  ;     replacetest2 ();     }    //  Requirements: Write a regular expression to match the phone number   first bit: Only 1 starts, second:35478  length: 11 bits      public static void matchesphone (String phone)  {         String reg =  "1[34578]\\d{9}";      &NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN (PHone.matches (REG)  ?  "Legal phone number"  :  "illegal mobile number")     }    //   demand, matching fixed telephone   Area code-host number   area code: First 0  length 3~4  host number:  first cannot be 0  length 7~8 bit      Public static void matchestel (String tel)  {         system.out.println (Tel.matches ("0\\d{2,3}-[1-9]\\d{6,7}")  ?  "legal landline":  "illegal landline");     }    //  Cut by Space     public static void  TestPlit1 ()  {        String str =  "Ming               Day     Place              false ";         string[] datas  = str.split (" +");         system.out.println ("Elements of an array"  + arrays.ToString (datas));    }        //  cut based on overlapping words     /*     *  groups and capture   capture groups can be numbered by calculating their opening brackets from left to right. For example, in the expression   ((A) (B (C)))  , there are four such groups:      *      *  1  ((A) (b (c)))  2 \A 3  (b (c))  4  (c)      *       *  Group 0 always represents the entire expression.   NOTE: Start the calculation group from the leftmost parenthesis      */    public static void  testplit2 ()  {        String str =  " Everybody's going to have a good time tomorrow. ";//  daming to Have fun         string[] datas =  str.split ("(.) \\1+ "); //  if the regular content needs to be reused, the regular content needs to be grouped, and the purpose of grouping is to improve the reuse of the regular. Group number cannot be specified, group number starting from 1          system.out.println ("element of the array"  + arrays.tostring (datas));     }        //  job: Write a regular match for a mailbox     / /  replacement     public static void replacetest1 ()  {         String str =  " Contact me: 13567012119 contact me: 13567012119 contact me: 13567012119 contact me: 13567012119 contact me: 13567012119 contact me: 13567012119 ";         String reg =  "1[34578]\\d{9}";         str = str.replaceall (reg,  "******");         system.out.println ("Post replaced:"  + str);    }     Public static void replacetest2 ()  {        string  str =  "I I I want to do a project item item";         string reg  =  "(.) \\1+ ";         str =&nBsp;str.replaceall ("(.) \\1+ ", ");//If you need to refer to the contents of the group in the ReplaceAll method, use the $ group number          System.out.println ("Post replaced:"  + str);     }}


package com.fish.regex;import java.util.regex.matcher;import java.util.regex.pattern;/* Lookup: A regular expression specified as a string must first be compiled into an instance of this class. The resulting regex can then be matched with any string used to create the  Matcher  object, which, according to the regular expression, can match any sequence of characters. All the states involved in performing a match reside in the match, so multiple matches can share the same pattern.   Therefore, the typical invocation order is   pattern p = pattern.compile ("canonical");  matcher m =  p.matcher ("Aaaaab");  boolean b = m.matches (); one match: boolean b =  Pattern.matches ("A*b",  "Aaaaab"); Find the method you need to use to match the image  1, Pattern (Regular object)  2, Matcher (Match object) you want to use: 1, find ()   Notifies the match to match the string, finds a string that conforms to the rule, returns true if it finds a string that matches the rule, otherwise returns FALSE2, group ()   get a substring of the rule that conforms to the rules note: When using the group method, Be sure to call the Find method first to let the match to find the matching string, otherwise error  */ public class Demo4 {     Public static void main (String[] args)  {         //wants to get a 3-letter word.         String str =  "da jia zhu yi&Nbsp;le,ming tian bu fang jia,xie xie! ";               string reg =   "\\b[a-za-z]{3}\\b";//First compile the string's regular into a Pattern object         Pattern  P = pattern.compile (reg);//Use regular object matching strings for   to produce a Matcher object          matcher m = p.matcher (str);                 system.out.println ("Do you have a string that matches the rules?") "+m.find ());  //Fetch once         system.out.println (" Get Results "+m.group ()) ;  //get one         system.out.println at a time ("Get Results" +m.group ());  // Get Once                 while ( M.find ())          {       &Nbsp;    //system.out.println (M.start () + "...." +m.end ());             //system.out.println ("Sub:" +str.substring (M.start (), M.end ()));             system.out.println (M.group ());         }            / /system.out.println (M.find ());//Match a rule to a string to find.         //system.out.println (M.find ());//Match a rule to a string to find.         //system.out.println (M.group ());//Before the group method is used, it must be found before it can be taken.     }}


Package com.fish.regex;/* Boundary Match ^ line end \b Word boundary word edit match only represents the beginning or end of a word, does not match any character \b non-word boundary \a input beginning \g last match \z output The end of the entry, only for the last terminator (if any) \z the end of the input */public class Demo5 {public static void main (string[] args) {System.out.printl    N ("Hello World", Matches ("hello\\b World"); }}


package com.fish.regex;import java.util.regex.matcher;import java.util.regex.pattern;/*  Web crawler (Web spider):  */public class demo6 {    // .com .cn . Com.cn .net    public static void main (String[] args)  {                string content  =  "There is nothing to contact:[email protected]  something is not contact: [email protected]";         String reg =  "[A-za-z1-9]\\w*@[a-za-z0-9]{2,} (\ \ com|cn|net) {;        // } "compiles the regular string to a regular object          pattern p = pattern.compile (REG);         //  using regular objects to produce a match object         matcher m =  p.matcher (content);                while  (M.find ())  {             system.out.println (M.group ());         }    }}


This article from "Small Fish Blog" blog, declined reprint!

Java Regular Expressions

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.