Java Tour (34)--custom server, urlconnection, Regular expression feature, match, cut, replace, fetch, web crawler

Source: Internet
Author: User


Java Tour (34)--custom server, urlconnection, Regular expression feature, match, cut, replace, fetch, web crawler

We then say network programming, TCP

I. Customizing the service side

We directly write a server, let the local to connect, you can see what kind of effect

Packagecom. LGL. Socket;Import Java. IO. IOException;Import Java. IO. PrintWriter;Import Java. NET. ServerSocket;Import Java. NET. Socket;public class Browserserver {//http://192.168. 1. 103:11000/public static void main (string[] Args) {try {serversocket ss = new ServerSocket (11000);Socket s = ss. Accept();System. out. println(s. Getinetaddress(). GetHostName() +":"+ S. Getinetaddress(). Gethostaddress());PrintWriter out= new PrintWriter (s. Getoutputstream(), True);  out. println("Hello Client");S. Close();Ss. Close();} catch (ioexception E) {//TODO auto-generated catch block E. Printstacktrace();}    }}

We run a direct access to Http://192.168.1.103:11000/and we know what the effect is.




Our console also prints out our address.




The interesting thing is that since the Web page is open, then he is supporting the html, we will output this sentence

out.println("<font color=‘red‘ size=‘30‘>Hello Client");

So you can see




Two. URLConnection

See the use of URLs first

Package Com.lgl.socket;import Java.net.malformedurlexception;import java.net.URL; public classUrldemo { public Static void Main(string[] Args) {Try{url URL =NewURL ("http://192.168.1.102/myweb/test.html?" Name=zhangsan&age=18 ");//agreementSystem. out. println (url.getprotocol ());//hostSystem. out. println (url.gethost ());//portSystem. out. println (url.getport ());//pathSystem. out. println (url.getpath ());//enquiry DepartmentSystem. out. println (url.getquery ()); }Catch(malformedurlexception E) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}

The results obtained




Keep Looking.

// 返回一个url连接对象URLConnection openConnection = url.openConnection();System.out.println(openConnection);InputStream inputStream = openConnection.getInputStream();bytenewbyte[1024];intlen = inputStream.read(buf);System.out.println(new String(buf, 0len));

Can actually read the stream, we get what we want from the stream

Three. Regular Expression features

Regular Expressions: You can understand the expression that conforms to a certain rule, although we don't use much, but it does apply, we mainly look at his use.

    • Specifically manipulating strings

We'll take a direct look at how we use

We now have a need

    • QQ number to perform the validation, requires 5-15 bits, can not start, can only be digital

Let's take a look at how our traditional approach is Calculated.

 public  class Test {  public Static void Main(string[] Args) {/** * to the QQ number to perform the validation, requires 5-15 bits, can not start, can only be the number * *String QQ ="11299923";intLen = Qq.length ();//length if(len >5&& Len <= the) {//cannot start with 0 if(!qq.startswith ("0")) {//all Numbers Char[] Chararray = Qq.tochararray ();BooleanFlag =false; for(inti =0; I < chararray.length; I++) {if(! (chararray[i] >=' 0 '&& chararray[i] <=' 9 ')) {flag =true; break; }                }if(flag) {System.err.println ("QQ:"+ qq); }Else{System.out.println ("non-pure numbers"); }            }Else{System.out.println ("0 does not begin to conform to specification"); }        }Else{System.out.println ("qq length has a problem"); }    }}

This is a very troublesome thing, and let's see how the regular expression is Expressed.

public   class  test1  { public  static  void  main  (string[] Args)        {String QQ =  "789152" ; /** * I just need to tell you right and Wrong. */ String regex =  "[1-9][0-9]{4,14}" ; boolean  flag = qq.matches (regex); if  (flag)        {System.out.println ( "qq:"  + qq);        } else  {System.out.println ( "error" ); }    }}

Very powerful, as long as a few lines of code can be displayed, ox, This symbol defines us to answer later

Four. match

It's a very powerful, we'll see what he Does.

    • Features: use some specific symbols to represent some code operations, which simplifies writing, and learning regular expressions is used to learn some special symbols.




    • 1. Match: matches

Let's take a look at this piece of code

"c"; /**         * 这个字符串只能是bcd中的其中一个,而且只能是一个字符         */ "[bcd]"; boolean flag = str.matches(reg);        System.out.println(flag);

The meaning of understanding clearly, in fact, a little more pleasing to the eye, we continue to

/**         * 这个字符的第二位是a-z就行         */ "[bcd][a-z]"; boolean flag1 = str.matches(reg);        System.out.println(flag1);

Is there a concept now? We continue, if I think now I am the first one is a letter the second is a number, how to spell it?

"[a-zA-Z][0-9]"; boolean flag2 = str.matches(reg2);    System.out.println(flag2);

General explanation, because I am not very familiar, hey

Five. Cutting

This cut, in string is also a cut split, and our regular, too, we continue to look

publicclass Test2 { publicstaticvoidmain(String[] args) { "zhangsan,lisi,wangwu"; ",";        String[] split = str.split(reg); for (String s : split) {            System.out.println(s);        }    }}

We output




Six. Replace

The regular expression is the operation of string, we look at the replacement

publicclass Test2 { publicstaticvoidmain(String[] args) { // 将数字连续超过五个替换成#号 replaceAll("fwfsda777777fs74666677s""\\d{5,}""#");    } publicstaticvoidreplaceAll(String str, String reg, String newStr) {        str = str.replaceAll(reg, newStr);        System.out.println(str);    }}

The results obtained




Seven. get
    • 1. Encapsulate a regular expression as an object
    • 2. Associate a regular expression with an object to manipulate
    • 3. After association, get the regular match engine
    • 4. Perform operations on rules-compliant substrings via the engine, such as removing the
    • /ul>
import java.util.regex.matcher;import java.util.regex.pattern;< Span class= "hljs-keyword" >public class  Test2 { Public  static  void  main  (string[] Args) {String string  =  "hello java android c cc CCC  C  "; //test  String reg =  "[a-z]" ; //to encapsulate the rules as objects  Pattern p = pattern.compile (reg); //to have the regular object associated with the string to be played, get the match object  Matcher Matcher = p.matcher (string ); System. out . println (matcher.matches ()); }}

It's a pattern that we can use to get strings.

Eight. web crawler

Crawler We are familiar with, also known as spiders, in fact, is to obtain some data, we can also use our regular in the acquisition function

Importjava.io.BufferedReader;Importjava.io.FileNotFoundException;Importjava.io.FileReader;Importjava.io.IOException;Importjava.util.regex.Matcher;Importjava.util.regex.Pattern; public  class Test2 {  public Static void Main(string[] Args) {    }/** * Gets the email address in the specified document */  public Static void Getemail() {Try{bufferedreader BUFR =NewBufferedReader (NewFileReader ("email.txt")); String line =NULL; String Emailreg ="\\[email protected]\\w+ (\\.\\w+) +"; Pattern p = pattern.compile (emailreg); while(line = Bufr.readline ())! =NULL) {System.out.println (line);//judgment MailboxMatcher m = P.matcher (line); while(m.find ()) {System.out.println (m.group ());//this will get all the Mailboxes.}            }        }Catch(filenotfoundexception E) {//TODO auto-generated Catch blockE.printstacktrace (); }Catch(ioexception E) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}

So we have all the mailbox number to get, of course, This is just a simple reptile concept, reptile Broad and profound, we have to learn the words should be a systematic understanding of the good!!!

okay, Our Java tour is over here too, and we're done with This.


Java Tour (34)--custom server, urlconnection, Regular expression feature, match, cut, replace, fetch, web crawler


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.