Java Regular Expression

Source: Internet
Author: User

As we all knowProgramDuring development, it is inevitable that a string needs to be matched, searched, replaced, and judged. These situations are sometimes complicated. If they are solved by pure encoding, it often wastes the programmer's time and energy. Therefore, learning and using regular expressions have become the main means to solve this contradiction.

As we all know, regular expressions are a specification that can be used for pattern matching and replacement. A regular expression is composed of common characters (such as characters A to Z) and special characters (metacharacters) it is used to describe one or more strings to be matched when the text subject is searched. A regular expression is used as a template to match a character pattern with the searched string.

Since jdk1.4 launched the java. util. RegEx package, we have provided a good Java Regular Expression application platform.

Because regular expressions are a complex system, I only want to introduce some concepts. For more information, see related books and explore them on your own.

\ Backslash

\ T interval ('\ u0009 ')

\ N line feed ('\ u000a ')

\ R press enter ('\ u000d ')

The \ D number is equivalent to [0-9].

\ D is equivalent to [^ 0-9].

\ S blank symbol [\ t \ n \ x0b \ f \ r]

\ S non-blank symbol [^ \ t \ n \ x0b \ f \ r]

\ W single character [a-zA-Z_0-9]

\ W non-single character [^ a-zA-Z_0-9]

\ F page feed

\ E escape

\ B boundary of a word

\ B a non-word boundary

End of the match before \ G

^ Starts with a limit.

^ Java conditions must start with Java

$ Is the end of the limit.

Java $ condition is limited to the end character of Java

. To limit any character

Java .. the condition is limited to any two characters except line breaks after Java

Add the specified condition "[]"

[A-Z] the condition is limited to one character in the lowercase A to Z range.

[A-Z] conditions are limited to one character in the upper case A to Z range

[A-Za-Z] the condition is limited to one character in the lowercase A to Z or uppercase A to Z range.

[0-9] the condition is limited to one character in the lowercase 0 to 9 Range

[0-9a-z] the condition is limited to one character in the lowercase 0 to 9 or A to Z range.

[0-9 [A-Z] the condition is limited to one character (intersection) in the lowercase 0 to 9 or A to Z range)

[] Add ^ and then add the restriction "[^]"

[^ A-Z] the condition is limited to one character in the range of non-lowercase A to Z

[^ A-Z] conditions are limited to one character in the range of not uppercase A to Z

[^ A-Za-Z] the condition is limited to one character in the range of non-lowercase A to Z or uppercase A to Z.

[^ 0-9] the condition is limited to one character in the range of 0 to 9 in non-lowercase letters.

[^ 0-9a-z] the condition is limited to one character in the range of 0 to 9 or A to Z in non-lowercase letters.

[^ 0-9 [A-Z] the condition is limited to one character (intersection) in the range of non-lowercase 0 to 9 or A to Z)

When the limit is 0 or more times for a specific character, you can use 「*」

J * more than 0 J

. * 0 or more arbitrary characters

J. * d j and D must contain more than 0 arbitrary characters.

When the condition is that a specific character appears more than once, you can use "+ 」

J + 1 or more J

. + 1 or more arbitrary characters

More than one arbitrary character between J. + d j and D

You can use "?" When the limit is 0 or more times for a specific character 「?」

Ja? J or ja appears

Limit to the number of consecutive occurrences of the specified character "{}」

J {2} jj

J {3} jjj

More than a characters, and "{,}」

J {3,} jjj, jjjj, jjjjj ,??? (More than three J events coexist)

More than one text, less than B "{a, B }」

J {3, 5} jjj, jjjj, or jjjjj

Take the two as "| 」

J | a j or

Java | Hello Java or hello

Specifies a combination type in "()".

For example, you can write <. * href = \". * \ "> (. + ?) </A>

When using the pattern. Compile function, you can add parameters that control the Matching Behavior of Regular Expressions:

Pattern pattern. Compile (string RegEx, int flag)

The flag value range is as follows:

Pattern. canon_eq is determined to be matched only when the "Canonical Decomposition" of the two characters are identical. For example, if this sign is used, the expression "a \ u030a" will match "? ". By default, canonical equivalence is not considered )".

Pattern. case_insensitive (? I) by default, Case Insensitive matching applies only to the US-ASCII character set. This flag allows the expression to ignore the case sensitivity for matching. To match a Unicode character with an unknown size, you just need to combine the unicode_case and the flag.

Pattern. Comments (? X) In this mode, space characters (in a regular expression) are ignored during matching ", it refers to the space in the expression, tab, and press Enter ). The comment starts from # And ends until the end of this line. You can enable the Unix line mode through the embedded flag.

Pattern. dotall (? S) In this mode, the expression '.' can match any character, including the end character of a row. By default, the expression '.' does not match the end character of the row.

Pattern. multiline

(? M) In this mode, '^' and '$' match the start and end of a row respectively. In addition, '^' still matches the start of the string, '$' also matches the end of the string. By default, these two expressions only match the start and end of the string.

Pattern. unicode_case

(? U) In this mode, If you enable the case_insensitive flag, it will match Unicode characters in case insensitive. By default, case-insensitive matching applies only to the US-ASCII character set.

Pattern. unix_lines (? D) In this mode, only '\ n' is considered as a row stop and matches'. ',' ^ ', and' $.

Aside from the vague concept, let's write a few simple Java regular use cases:

◆ For example, when the string contains Verification

// Search for any string starting with Java and ending

Pattern pattern = pattern. Compile ("^ java .*");

Matcher = pattern. matcher ("Java is not a person ");

Boolean B = matcher. Matches ();

// If the condition is met, true is returned; otherwise, false is returned.

System. Out. println (B );

◆ When a string is separated by multiple conditions

Pattern pattern = pattern. Compile ("[, |] + ");

String [] STRs = pattern. Split ("Java Hello World Java, hello, world | sun ");

For (INT I = 0; I <STRs. length; I ++ ){

System. Out. println (STRs [I]);

}

◆ Text replacement (first occurrence of characters)

Pattern pattern = pattern. Compile ("Regular Expression ");

Matcher = pattern. matcher ("Regular Expression Hello world, regular expression Hello World ");

// Replace the first regular data

System. Out. println (matcher. replacefirst ("Java "));

◆ Text replacement (all)

Pattern pattern = pattern. Compile ("Regular Expression ");

Matcher = pattern. matcher ("Regular Expression Hello world, regular expression Hello World ");

// Replace the first regular data

System. Out. println (matcher. replaceall ("Java "));

◆ Text replacement (replacement character)

Pattern pattern = pattern. Compile ("Regular Expression ");

Matcher = pattern. matcher ("Regular Expression Hello world, regular expression Hello World ");

Stringbuffer SBR = new stringbuffer ();

While (matcher. Find ()){

Matcher. appendreplacement (SBR, "Java ");

}

Matcher. appendtail (SBR );

System. Out. println (SBR. tostring ());

◆ Verify whether the email address is used

String STR = "ceponline@yahoo.com.cn ";

Pattern pattern = pattern. compile ("[\ W \\. \-] + @ ([\ W \-] + \\.) + [\ W \-] + ", pattern. case_insensitive );

Matcher = pattern. matcher (STR );

System. Out. println (matcher. Matches ());

◆ Remove HTML tags

Pattern pattern = pattern. Compile ("<. +?> ", Pattern. dotall );

Matcher = pattern. matcher ("<a href = \" index.html \ "> homepage </a> ");

String string = matcher. replaceall ("");

System. Out. println (string );

◆ Search for the corresponding condition string in HTML

Pattern pattern = pattern. Compile ("href = \" (. + ?) \"");

Matcher = pattern. matcher ("<a href = \" index.html \ "> homepage </a> ");

If (matcher. Find ())

System. Out. println (matcher. Group (1 ));

}

◆ Intercept http: // address

// Intercept the URL

Pattern pattern = pattern. Compile ("(http: // | https: //) {1} [\ W \. \-/:] + ");

Matcher = pattern. matcher ("dsdsds
Stringbuffer buffer = new stringbuffer ();

While (matcher. Find ()){

Buffer. append (matcher. Group ());

Buffer. append ("\ r \ n ");

System. Out. println (buffer. tostring ());

}

◆ Replace the specified {} text

String STR = "Java's current development history is from {0}-{1} years ";

String [] [] object = {New String [] {"\\{ 0 \\}", "1995 "}, new String [] {"\\{ 1 \}"," 2007 "}};

System. Out. println (replace (STR, object ));

Public static string Replace (final string sourcestring, object [] Object ){

String temp = sourcestring;

For (INT I = 0; I <object. length; I ++ ){

String [] result = (string []) object [I];

Pattern pattern = pattern. Compile (result [0]);

Matcher = pattern. matcher (temp );

Temp = matcher. replaceall (result [1]);

}

Return temp;

}

◆ Query files in a specified directory with regular conditions

// Used to cache the file list

Private arraylist files = new arraylist ();

// Used to carry the file path

Private string _ path;

// It is used to carry the unmerged regular expression.

Private string _ Regexp;

Class myfilefilter implements filefilter {

/**

* Matching file name

*/

Public Boolean accept (File file ){

Try {

Pattern pattern = pattern. Compile (_ Regexp );

Matcher match = pattern. matcher (file. getname ());

Return match. Matches ();

} Catch (exception e ){

Return true;

}

}

}

/**

* Parse the input stream

* @ Param inputs

*/

Filesanalyze (string path, string Regexp ){

Getfilename (path, Regexp );

}

/**

* Analyze the file name and add files

* @ Param Input

*/

Private void getfilename (string path, string Regexp ){

// Directory

_ Path = path;

_ Regexp = Regexp;

File directory = new file (_ path );

File [] filesfile = directory. listfiles (New myfilefilter ());

If (filesfile = NULL) return;

For (Int J = 0; j <filesfile. length; j ++ ){

Files. Add (filesfile [J]);

}

Return;

}

/**

* Display output information

* @ Param out

*/

Public void print (printstream out ){

Iterator elements = files. iterator ();

While (elements. hasnext ()){

File file = (File) elements. Next ();

Out. println (file. getpath ());

}

}

Public static void output (string path, string Regexp ){

Filesanalyze filegroup1 = new filesanalyze (path, Regexp );

Filegroup1.print (system. Out );

}

Public static void main (string [] ARGs ){

Output ("C: \", "[A-z |.] *");

}

There are many other functions of Java regular expressions. In fact, as long as it is character processing, there will be no things that cannot be done by regular expressions. (Of course, regular expression interpretation is time-consuming. | ......)

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.