Regular Expression-2 (Java)

Source: Internet
Author: User

I also implemented one in Java, and found that the regular expressions in Java are slightly different, and I also felt that the reading and writing files in Java are not elegant.

/*
* Created on 2004-10-1
*/
Import java. util. RegEx .*;
Import java. Io .*;

/**
* @ Author dancefire
*/
Public class datafilter {

Public static void main (string [] ARGs ){
If (ARGs. Length <2)
{
System. Err. println ("Please enter 2 filenames (e.g. in.txt out.txt )");
Return;
}
String strin = NULL, Strout = NULL;

// Get string from a file
StrIn = readFile (args [0]);
// Process
StrOut = filter (strIn );
// Store Result into a file
WriteFile (args [1], strOut );

}
Private static void writeFile (String filename, String data)
{
BufferedWriter wr = null;
Try {
Wr = new BufferedWriter (new FileWriter (filename ));
Wr. write (data );
} Catch (Exception e)
{
E. printStackTrace ();
} Finally {
Try {
If (wr! = Null)
Wr. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
}
Return;
}
Private Static string readfile (string filename)
{
String strret = NULL;
Bufferedreader RD = NULL;
Try {
RD = new bufferedreader (New filereader (filename ));
String line = NULL;
Stringbuffer sb = new stringbuffer ();
While (line = RD. Readline ())! = NULL)
{
SB. append (line );
}
StrRet = sb. toString ();
} Catch (Exception e)
{
E. printStackTrace ();
} Finally {
Try {
If (rd! = Null)
Rd. close ();
} Catch (Exception e ){
E. printstacktrace ();
}
}
Return strret;
}
Private Static string filter (string input)
{
Pattern P = pattern. Compile ("/" (// W +) :( // W +) % (// W + )/"");
Matcher M = P. matcher (input );
Stringbuffer sb = new stringbuffer ();
While (M. Find ())
{
Sb. append (m. group (1) + ":" + m. group (2) + "*" + m. group (3) + "," + System. getProperty ("line. separator "));
}
Return sb. toString ();
}
}

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.