Basics of Java Regular Expressions (required for beginners) and basics of Regular Expressions

Source: Internet
Author: User

Basics of Java Regular Expressions (required for beginners) and basics of Regular Expressions

A regular expression is a regular expression that can be used for pattern matching and replacement. a regular expression consists 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.

As we all know, in program development, it is inevitable that a string needs to be matched, searched, replaced, and judged. These situations are sometimes complicated. If they are solved in pure encoding mode, 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 the boundary of a word
/B a non-word boundary
The 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
. The condition limits any single character except/n.
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. 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, after 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 the size of 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 that starts with Java and ends with Pattern pattern = Pattern. compile ("^ Java. * "); Matcher matcher = pattern. matcher ("Java is not a person"); boolean B = matcher. matches (); // if the condition is met, true is returned; otherwise, false System is returned. 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 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 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 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 matcher = pattern. matcher (str );
System. out. println (matcher. matches ());

◆ Remove html tags

Pattern pattern = Pattern. compile ("<. +?> ", Pattern. DOTALL); Matcher 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 matcher = pattern. matcher ("<a href =/" index.html/"> homepage </a>"); if (matcher. find () System. out. println (matcher. group (1 ));}

◆ Intercept http: // address

// Intercept urlPattern pattern = Pattern. compile ("(http: // | https: //) {1} [// w //. //-/:] + "); Matcher matcher = pattern. matcher ("dsdsds 

◆ 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 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; // used to carry the unmerged regular formula private String _ regexp; class MyFileFilter implements FileFilter {/*** match File name */public boolean accept (file 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.