Java Regular Expression getting started,

Source: Internet
Author: User

Java Regular Expression getting started,

Many languages, including Perl, PHP, Python, JavaScript, and JScript, support regular expressions for text processing. Some text editors use regular expressions to implement advanced search-replace functions. Therefore, the JAVA language is no exception. Regular expressions have exceeded the limits of a language or system and become a widely used tool. We can use them to solve some practical problems encountered in actual development.

I. Basic knowledge of Regular Expressions
1.1 periods
Assume that you are playing an English spelling game and want to find three letters of words. These words must start with a letter "t" and end with a letter "n. In addition, if you have an English dictionary, you can use a regular expression to search for all its contents. To construct this regular expression, you can use the wildcard ".". In this way, the complete expression is "t. n. It matches "tan", "ten", "tin", "ton", and "t # n", "tpn", and even "t n ", there are many other meaningless combinations. This is because the periods match all characters, including spaces, Tab characters, and even line breaks:
1.2 square brackets
To solve the problem that the period matching range is too wide, you can specify meaningful characters in square brackets. In this case, only the characters specified in square brackets are involved in the matching. That is to say, the regular expression "t [aeio] n" only matches "tan", "Ten", "tin", and "ton ". But "Toon" does not match, because within square brackets you can only match a single character:
1.3 "or" symbol
If you want to match "toon" in addition to all the words matched above, you can use the "|" operator. The basic meaning of the "|" operator is the "or" operation. To match "toon", use the regular expression "t (a | e | I | o | oo) n. Square brackets cannot be used here, because square brackets can only match a single character. square brackets () must be used here. Parentheses can also be used for grouping.
1.4 indicates the number of matches
The following table shows the regular expression syntax:

Table 1.1 regular expression syntax

Suppose we want to search for American Social Security numbers in text files. The number is in the format of 999-99-9999. The regular expression 1 used to match it is shown in. In a regular expression, A hyphen (-) has a special meaning. It represents a range, for example, from 0 to 9. Therefore, when matching a hyphen in a social security number, it must be preceded by an escape character "/".

Assume that you want a hyphen to appear or not to appear during the search -- that is, 999-99-9999 and 999999999 are in the correct format. In this case, you can add "?" After the hyphen. Quantity limit symbol.

An American car license is in four digits with two letters. Its regular expression is preceded by the digit section "[0-9] {4}", plus the letter section "[A-Z] {2 }".
1.5 "no" symbol
The "^" symbol is called the "no" symbol. If it is used in square brackets, "^" indicates the character that you do not want to match. For example, the regular expression matches all words, except words starting with an "X" letter.
1.6 parentheses and white spaces
The "/s" symbol is a white space symbol that matches all blank characters, including Tab characters. If the string matches correctly, how can we extract the month part? You only need to add a parentheses around the month to create a group, and then use oro api to extract its value.
1.7 other symbols
For simplicity, you can use shortcuts created for common regular expressions. See the following figure:
/T: tab, equivalent to/u0009
/N: Line Break, equivalent to/u000A
/D: represents a number, which is equivalent to [0-9].
/D: indicates a non-number, which is equivalent to [^ 0-9].
/S: blank characters such as line breaks and Tab tabs
/S: Non-blank characters
/W: letter, equivalent to [a-zA-Z_0-9]
/W: Non-letter character, equivalent to [^/w]
For example, in the previous example of a Social Security number, we can use "/d" for all the places where "[0-9]" appears ".
II. The following are my programs for your reference:

Package org. luosijin. test; import java. util. regex. matcher; import java. util. regex. pattern; public class Regex {public static void main (String [] args) {Pattern pattern = Pattern. compile ("B * g"); Matcher matcher = pattern. matcher ("bbg"); System. out. println (matcher. matches (); System. out. println (pattern. matches ("B * g", "bbg"); // verify the zip code System. out. println (pattern. matches ("[0-9] {6}", "200038"); System. Out. println (pattern. matches ("// d {6}", "200038"); // verify the phone number System. out. println (pattern. matches ("[0-9] {3, 4 }//-? [0-9] + "," 02178989799 "); getDate (" Nov "); charReplace (); // verify the ID card: determines whether a string is an ID card number, whether it is a 15-or 18-digit number. System. out. println (pattern. matches ("^ // d {15} | // d {18} $", "123456789009876"); getString ("D:/dir1/test.txt "); getChinese ("welcome to china, Jiangxi fengxin, welcome, you! "); ValidateEmail (" luosijin123@163.com ");}/*** date extraction: extract the month */public static void getDate (String str) {String regEx = "([a-zA-Z] +) | // s + [0-9] {1, 2 }, // s * [0-9] {4} "; Pattern pattern = Pattern. compile (regEx); Matcher matcher = pattern. matcher (str); if (! Matcher. find () {System. out. println ("Date Format error! "); Return;} System. out. println (matcher. group (1); // the index value of the group starts from 1, so the method for obtaining the first group is m. group (1) instead of m. group (0 ). }/*** Character replacement: In this example, replace all the places in a string that contain one or more consecutive "A" with "". */Public static void charReplace () {String regex = "a +"; Pattern pattern = Pattern. compile (regex); Matcher matcher = pattern. matcher ("okaaaa LetmeAseeaaa aa booa"); String s = matcher. replaceAll ("A"); System. out. println (s);}/*** String extraction */public static void getString (String str) {String regex = ". + /(. +) $ "; Pattern pattern = Pattern. compile (regex); Matcher matcher = pattern. matcher (str); if (! Matcher. find () {System. out. println ("the file path format is incorrect! "); Return;} System. out. println (matcher. group (1);}/*** Chinese extract * @ param str * @ author Lusi Jin * @ date 12:27:17 */public static void getChinese (String str) {String regex = "[// u4E00-// u9FFF] +"; // [// u4E00-// u9FFF] indicates the Chinese character Pattern pattern = Pattern. compile (regex); Matcher matcher = pattern. matcher (str); StringBuffer sb = new StringBuffer (); while (matcher. find () {sb. append (matcher. group ();} System. out. println (sb);} public static void validateEmail (String email) {String regex = "[0-9a-zA-Z] + @ [0-9a-zA-Z] + //. [0-9a-zA-Z] + "; Pattern pattern = Pattern. compile (regex); Matcher matcher = pattern. matcher (email); if (matcher. matches () {System. out. println ("this is a valid Email");} else {System. out. println ("this is an invalid Email ");}}}

The above is all the content of the Java regular expression. I hope it will be helpful for your learning.

Articles you may be interested in:
  • Java Regular Expressions
  • Java Regular Expression verification function
  • Java Regular Expressions
  • JAVA Regular Expressions Pattern and Matcher
  • Java Regular Expression functions and applications
  • Use regular expressions in Java/Js to match Nested Html tags
  • Java Regular Expression learning summary and some small examples
  • Java uses regular expressions to extract () Content
  • Example of java regular expression to extract numbers
  • Java Regular Expression verification email and phone number example

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.