Java Foundation 10: Regular Expressions and reflections

Source: Internet
Author: User

 

On the Java foundation of the article, I think it can also be written in my other blog, is definitely original, and now share to everyone out.

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------

First, regular expression
I. Overview1. Concept:

Regular expressions, also known as formal notation, conventional notation, a concept of computer science. A regular expression uses a single string to describe and match a series of strings that conform to a certain syntactic rule. In many text editors, regular expressions are often used to retrieve and replace text that conforms to a pattern.

Many programming languages support the use of regular expressions for string manipulation.

A regular expression is a logical formula for a string operation, which is a "rule string" that is used to express a filter logic for a string, using predefined specific characters and combinations of these specific characters.

2. function

Given a regular expression and another string, we can achieve the following purposes:

    1. whether the given string conforms to the filtering logic of the regular expression (called "Match");

    2. You can get the specific part we want from the string using a regular expression.

3, the regular expression is characterized by:

    1. Flexibility, logic and functionality are very strong;

    2. Complex control of strings can be achieved quickly and in a very simple way.

    3. for people who have just come into contact, it is more obscure and difficult to understand.

second, common functions1, matching

The matches method of String

<span style= "White-space:pre" ></span>/** * QQ number Verification requirements: length 5-15 digits, cannot start with 0 */private static void Fun2 () {String s = "023"; Boolean B = s.matches ("[1-9][0-9]*{4,14}"); b = S.matches ("[1-9]\\d*{4,14}");//Equal System.out.println (b);}


2, cutting

the split () method of String

<span style= "White-space:pre" ></span>/** * Cutting method */private static void Fun3 () {//Cut space string s = "AfDF            DFSF D         Dafa "; string[] names = S.split ("+"); for (String name:names) {System.out.println (name);} Cut the overlapping word string S1 = "Afdfaaaaaaadfsfdssdafa"; string[] Mynames = S.split ("(.) \\1+ "); for (String name:mynames) {System.out.println (name);}}


3, replace

The replaceall () method of the String

<span style= "White-space:pre" ></span>/** * replace */private static void Fun4 () {String S1 = "Afdfaaaaaaadfsfdssda FA "; String s = S1.replaceall ("(.) \\1+ "," $ "); System.out.println (s);}



4, get

Matcher Find () method, finds the next sub-sequence

Matcher Group () method that returns the input subsequence that was matched by the previous match operation

/** * gets */private static void Fun5 () {Pattern p = pattern.compile ("a*b");//encapsulates regular rules as objects matcher m = P.matcher ("AAAAABAAABDFD FAAABSS ");//The matching string is encapsulated into object Boolean B = m.matches ();//m.find ();//system.out.println (m); while (M.find ()) { System.out.println (M.group ());}}


Third, web crawler

Web crawler sounds fun, but the truth is very simple, is to get the data of the specified rules on the Internet

The specified rule can use regular expressions to write

public class Pachong {public static void main (string[] args) throws Exception {list<string> List = fun1 (); for (Strin G name:list) {System.out.println (name);}} /** * @throws Exception  *  */private static list<string> fun1 () throws Exception {URL url = new URL ("HTTP://1 27.0.0.1:8080/myweb/test.html "); InputStream in = Url.openstream (); BufferedReader bufr = new BufferedReader (new InputStreamReader (in)); arraylist<string> list = new arraylist<string> (); String Main_rgex = "\\[email protected]\\w+ (\\.\\w+) +"; Pattern p =pattern.compile (Main_rgex); String line = null;while (line = Bufr.readline ())! = null) {Matcher m = p.matcher (line), while (M.find ()) {List.add (M.group ( ));}} return list;}}



Second, reflection


One, overview

1. Definition

Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class;

For any object, it can call any of its methods and properties;

This dynamic acquisition of information and the ability to dynamically invoke the object's methods is called the reflection mechanism of the Java language.  

Dynamically fetching the information in the class is Java reflection.


2. Reflection Benefits

The reflection technology greatly improves the expansibility of the program.


3, the Java reflection mechanism mainly provides the following functions:

Determine the class to which any object belongs at run time;

Constructs an object of any class at run time;

Determine the member variables and methods of any class at run time;

A method of invoking any object at run time;

Generating dynamic agents


second, get the Class Object
public static void Getclassobject_3 () throws ClassNotFoundException {String className = "Cn.itcast.bean.Person"; Class clazz = Class.forName (className); System.out.println (clazz);}



third, get the constructor function in class
<span style= "White-space:pre" ></span>/** * Create an instance with parameters * @throws Exception  */private static void Fun2 () Throws Exception {String name = "Jinfulin.b.bean"; Class clazz = class.forname (name); Constructor cons = Clazz.getconstructor (string.class,int.class); Object obj = cons.newinstance ("SF", 21);} /** * Creates a new, parameterless instance */private static void Fun1 () throws Classnotfoundexception,instantiationexception, illegalaccessexception {String name = "Jinfulin.p.bean.person"; Class clazz = class.forname (name), Object obj = Clazz.newinstance ();//Create a new parameterless instance System.out.println (obj);}




Iv. getting the fields in class
Field field = Null;clazz.getfield ("Age");//Only get public field = Clazz.getdeclaredfield ("Age");//Get only this class, but contain private. Access to the private field cancels the permission check. Violent visits. Field.setaccessible (True);p rivate static void Getfiledemo () throws Exception {Class clazz = Class.forName (" Jinfulin.p.bean.person "); Field field = Null;field = Clazz.getdeclaredfield ("name");//gets only this class, but contains the private fields. Field.setaccessible (TRUE);//access to the private field cancels the permission check. Violent visits. Object obj = Clazz.newinstance (); Field.set (obj, "Jinfoling"); object o = Field.get (obj); System.out.println (o);}


Iv. getting the method in class
<span style= "White-space:pre" ></span>method[] Methods  = Clazz.getmethods ();//Gets public methods. Methods = Clazz.getdeclaredmethods ();//Only get all methods in this class, including private. Method.invoke (obj, "Xiao Qiang", 89);//Set the parameter value public static void Getmethoddemo_3 () throws Exception {Class clazz = Class.forName (" Cn.itcast.bean.Person "); Object obj = Clazz.newinstance (); method = Clazz.getmethod ("Parammethod", String.class,int.class), Method.invoke (obj, "Xiao Qiang", 89);


Third, the last


Regular expressions are simple to use, but complex and readable, however, regular expressions of some common strings, such as mailboxes, social Security numbers, etc. can be found on the Internet, and it is good to use them.

Reflection technology is more important, reflection can also be combined with the abstract Factory mode to replace the DB, the reflective knowledge will be discussed later.






Java Foundation 10: Regular Expressions and reflections

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.