Java basics-Regular Expressions

Source: Internet
Author: User

Java basics-Regular Expressions
1. Why is a regular expression required? Regular Expressions can easily match data and perform more complex string verification, splitting, and replacement functions. For example, to determine whether a String is composed of digits, if a regular expression is not used, the Code is as follows: public static boolean isAllNum (string) {char [] charArr = String. toCharArray (); for (char tempC: charArr) {if (tempC <'0' | tempC> '9') // determines whether each character is in '0 '~ Return false between '9';} return true;} Now only checks whether the string is composed of digits only. If it is a little more complex, the code will be larger. If you use a regular expression, the Code is as follows: public static boolean isAllNum2 (String string) {if (Pattern. compile ("[0-9] + "). matcher (string ). matches () return true; else return false;} For methods using regular expressions, the key code is a line, that is, the second line. Comparing the two sections of code, we will find the advantage of using regular expressions, especially when the string processing logic is complicated, the advantage of Regular Expressions will be more prominent. (I will explain the code in detail in the next article, I will slowly introduce O (lead _ lead) O ). 2. the Pattern class and the Mattern class Pattern class are compiled expressions of regular expressions. Regular Expressions specified as strings must first be compiled into instances of this class, then you can use the obtained mode to create a Matcher object. Matcher is an interpreter. It interprets Regular Expression matching by Pattern, and then calls the matches method to obtain matching results. You may see it a little fuzzy. In fact, the basic operation process is: Pattern p = Pattern. compile ("[0-9] +"); // The parameter is a regular expression Matcher m = p. matcher ("aaaaab"); // The parameter is the string to be matched. boolean B = m. matches (); // return the abbreviated form of the matching result, that is, the form in the first example: Pattern. compile ("Regular Expression "). matcher ("data to be matched "). matches (); the most common method in the Pattern class is String [] strArr = split (CharSequence string). This method is used to split string strings according to regular expression rules, returns the split character array. Common methods in the Matcher class: public boolean matches (); // perform String verification public String replaceAll (String replacement); // replace String 3. the common regular expression rules are not named. The number of characters is incorrect (X indicates a set of rules). For example, Pattern is not named. compile ("[0-9]"). matcher ("123 "). matches (); if [0-9] is used to match the string "123", false is returned because [0-9] is a set of specifications, and nothing is returned afterwards, it indicates that it must appear only once. Therefore, the matched string can only be one character. The return result is true only when "123" is changed to "1. For example, use regular expressions: [0-9]?, If this regular expression is used to match an empty string: ", the return result is true because X? It can appear 0 times or 1 time. Therefore, if [0-9] + is used, strings of any size can be matched. For another example, if the regular expression [0-9] {2,} is used, only the length of the string matched by this regular expression is greater than or equal to 2, and the string is composed of digits to return true. For example, when we register a user online, the user name must be 6-9 digits or letters, you can use the regular [a-zA-Z0-9] {6, 9} for matching. The logic operator (X, Y indicates a set of specifications) is not named for help understanding. Here are several examples to verify the above regular expression rules: Example 1: verify whether a string is in a valid date format (yyyy-MM-dd). Because year 4 is an integer, month and day are two integers separated, therefore, the regular expression can be: "\ d {4}-\ d {2}-\ d {2}" because the slash \ In \ d is not an escape character, therefore, we need to escape it. Therefore, we need two slash codes: public static boolean isDate (String string) {String regex = "\ d {4}-\ d {2}-\ d {2}"; // Regular Rule Pattern p = Pattern. compile (regex); // create a Pattern object and compile the regular expression Matcher m = p. matcher (string); // create the Matcher object return m. ma Tches ();} Example 2: Split the English words in the string "Pairs32London0Beijing7893Hangzhou" into the following code. // we can see from the string that the quote characters are separated by numbers, therefore, we only need to use the number as the separator String str = "Pairs32London0Beijing7893Hangzhou"; Pattern p = Pattern. compile ("\ d +"); String [] strArr = p. split (str); for (String tempStr: strArr) {System. out. println (tempStr);} Example 3: replace all spaces in the string "a B C D" with underscores "_" as follows: /*** replace spaces in the string "a B C D" with underscores "_" */public static void test2 () {Stri Ng string = "a B C D"; String regex = "\ s"; // matches all blank characters, including spaces and line breaks Pattern p = Pattern. compile (regex); Matcher matcher = p. matcher (string); System. out. println (matcher. replaceAll ("_");} 4. the String class supports regular expressions. After JDK1.4, Java expands the regular expressions and starts to directly support regular expressions in the String class. For example, replace all the numbers in the "haha1heihei123xixi0" String with the "_": String str = "haha1heihei123xixi0"; str = str. replaceAll ("\ d +", "_"); System. out. println (str );

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.