Java and regular expressions

xiaoxiao2021-03-06  87

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

Regular expressions and Java programming languages

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

Class and method

The following class matches the character sequence based on the mode specified by the regular expression.

Pattern class

An example of the Pattern class represents the regular expression specified in the string, which is similar to the syntax used by Perl.

The regular expression specified in the form of a string must be compiled into an instance of the Pattern class. The generated mode is used to create a Matcher object, which matches any character sequence according to the regular expression. Multiple matches can share a mode because it is unique.

Compile a given regular expression into a mode with the Compile method, then create a match with the Matcher method, which will match the given input according to this mode. The Pattern method returns the regular expression used by compiling this mode.

The SPLIT method is a convenient method that cuts a given input sequence separately in a location that matches this mode. The following example demonstrates:

/ *

* Separates the input string separated by commas and / or spaces with Split.

* /

Import java.util.regex. *;

PUBLIC CLASS SPLITTER {

Public static void main (string [] args) throws exception {

// Create a pattern to match breaks

Pattern P = Pattern.Compile ("[, // s] ");

// split input with the pattern

String [] result =

P.Split ("One, Two, Three Four, Five");

For (int i = 0; i

System.out.println (Result [i]);

}

}

Matcher class

An instance of the Matcher class is used to match the character sequence according to a given string sequence mode. Use the Charsequence interface to provide the input to the match to support matching of characters from a variety of input sources.

Generate a match from this mode by calling a Matcher method of a pattern. After the match is created, you can use it to perform three different matching operations:

The Matches method is attempting to match the entire input sequence based on this mode.

The LOOKINGAT method is attempting to match the input sequence from the beginning based on this mode.

The Find method will scan the input sequence and look for the next place matching the pattern.

These methods return a Boolean value indicating success or failure. If the match is successful, you can get more information by querying the status of the match.

This class also defines the method of replacing the matching sequence with a new string. If the content of these strings can be derived from the matching result.

The appendreplacement method first adds all characters between the current location to the next matching position, then add the replacement value. AppendTail is added to the string from the last matching position until the end of the end.

For example, in the string Blahcatblahcatblah, the first AppendReplacement adds Blahdog. The second appendreplacement adds Blahdog, then AppendTail adds Blah, generated: Blahdogblahdogblah. See the example of a simple word.

Charsequence interface

The Charsequence interface provides unified read-only access to many different types of character sequences. You provide data to search from different sources. Using String, StringBuffer, and Charbuffer, charsequence, so you can easily get the data to search from them. If these available data sources are not suitable, you can write your own input source by implementing a Charsequence interface. Regex scenario example

The following code example demonstrates the usage of java.util.Regex packages in a variety of common situations:

Simple word replacement

/ *

* This Code Writes "One Dog, Two dogs in the Yard."

* To The Standard-Output Stream:

* /

Import java.util.regex. *;

Public class replacement {

Public static void main (string [] args)

Throws exception {

// Create a pattern to match cat

Pattern P = Pattern.Compile ("cat");

// Create a matcher with an input string

Matcher M = P.matcher ("One Cat,"

"Two cats in the yard");

StringBuffer SB = new stringbuffer ();

Boolean Result = m.find ();

// loop through and create a new string

// with the replacements

While (result) {

M.AppendReplacement (SB, "DOG");

Result = m.find ();

}

// Add the last segment of infut to

// the new string

M.AppendTail (SB);

System.out.println (sb.toString ());

}

}

Email confirmation

The following code is such an example: You can check that some characters are not an email address. It is not a complete, suitable for all possible email confirmations, but you can add it when you need it.

/ *

* Checks for Invalid Characters

* in email addresses

* /

Public class emailvalidation {

Public static void main (string [] args)

Throws exception {

String infut = "@ sun.com";

// Checks for Email Addresses Starting with

// INAPPRIATE SYMBOLS LIKE DOTS OR @ Signs.

Pattern P = Pattern.Compile ("^ //. | ^ @");

Matcher M = P.matcher (Input);

IF (m.find ())

System.err.Println ("Email Addresses Don't start"

"with dots or @ signs.");

// Checks for Email Addresses That Start with

// www. andprints a message if it@es.

P = pattern.Compile ("^ www //."); m = p.matcher (input);

IF (m.find ()) {

System.out.println ("Email Addresses Don't Start"

"with /" www./ ", Only Web Pages do.");

}

P = pattern.Compile ("[^ a-za-z0-9 ////@_//- ~ #] ");

m = p.matcher (input);

StringBuffer SB = new stringbuffer ();

Boolean Result = m.find ();

Boolean deletedillegalchars = false;

While (result) {

deletedillegalchars = true;

M.AppendReplacement (SB, ");

Result = m.find ();

}

// add the last segment of infut to the new string

M.AppendTail (SB);

INPUT = sb.toString ();

IF (deletedillegalchars) {

System.out.println ("IT Contained IncorRect Characters

", Such as spaces or comms.");

}

}

}

Remove control characters from a file

/ * This class removes control characters from a name

* file.

* /

Import java.util.regex. *;

Import java.io. *;

Public class control {

Public static void main (string [] args)

Throws exception {

// Create a file object with the file name

// in the argument:

FILE FIN = New File ("FileName1");

File fout = new file ("filename2");

// Open and INPUT and OUTPUT Stream

FileInputStream Fis =

New FileInputStream (FIN);

FileOutputStream Fos =

New FileOutputStream (fout);

BufferedReader in = New BufferedReader

New InputStreamReader (FI);

BufferedWriter out = new bufferedwriter

New OutputStreamWriter (FOS));

// the pattern matches control character

Pattern P = Pattern.Compile ("{cntrl}");

Matcher m = p.matcher ("");

String aline = null;

While ((aline = in.readline ())! = null) {

M.Reset (aline);

// Replaces Control Characters with An Empty

// String.

String result = m.replaceAll (""); out.write (result);

Out.newline ();

}

In.Close ();

Out.close ();

}

}

File look

/ *

* Prints Out the Comments Found in a .java file.

* /

Import java.util.regex. *;

Import java.io. *;

Import java.nio. *;

Import java.nio.charset. *;

Import java.nio.channels. *;

Public class charbufferexample {

Public static void main (string [] args) throws exception {

// Create a pattern to match Comments

Pattern P =

Pattern.Compile ("//.* $", pattern.multiline;

// Get a channel for the source file

File f = new file ("replacement.java");

FileInputStream Fis = New FileInputStream (f);

FileChannel Fc = fis.getchannel ();

// Get a charbuffer from the source file

Bytebuffer bb =

fc.map (filechannel.map_ro, 0, (int) fc.size ());

Charset cs = charset.Forname ("8859_1");

CharSetDecoder CD = cs.newdecoder ();

Charbuffer CB = CD.DECode (bb);

// Run Some Matches

Matcher m = p.matcher (cb);

While (m.find ())

System.out.println ("Found Comment:" m.Group ());

}

}

in conclusion

The pattern match in the Java programming language is now as flexible in many other programming languages. Regular expressions can be used in applications to ensure that data is correct before entering the database or sends to the application, and the regular expression can also be used for a wide variety of management. In short, in Java programming, regular expressions can be used in any way that needs mode matching.

转载请注明原文地址:https://www.9cbs.com/read-106196.html

New Post(0)