Java Regular Expression learning tutorial,

Source: Internet
Author: User

Java Regular Expression learning tutorial,

This tutorial aims to help you navigate Java Regular Expressions and also help me review regular expressions.

What is a regular expression?

The regular expression defines the string mode. Regular Expressions can be used to search, edit, or process text. Regular expressions are not limited to a specific language, but are slightly different in each language. Java regular expressions are the most similar to Perl expressions.

Java Regular Expression classes are included in the java. util. regex package. There are three classes:Pattern, MatcherAndPatternSyntaxException.

The Pattern object is the compiled version of the regular expression. There is no public constructor. We pass a regular expression parameter to the public static method compile to create a pattern object.
Matcher is a regular engine object used to match the input string and the created pattern object. This class does not have any public constructor. We use the matcher method of the patten object and use the input string as the parameter to obtain a Matcher object. Then, use the matches method and return a Boolean value to determine whether the input string matches the regular expression.
If the regular expression syntax is incorrect, the PatternSyntaxException is thrown.
Let's look at how these classes are used in a simple example.

package com.journaldev.util; import java.util.regex.Matcher;import java.util.regex.Pattern; public class RegexExamples {   public static void main(String[] args) {    // using pattern with flags    Pattern pattern = Pattern.compile("ab", Pattern.CASE_INSENSITIVE);    Matcher matcher = pattern.matcher("ABcabdAb");    // using Matcher find(), group(), start() and end() methods    while (matcher.find()) {      System.out.println("Found the text \"" + matcher.group()          + "\" starting at " + matcher.start()          + " index and ending at index " + matcher.end());    }     // using Pattern split() method    pattern = Pattern.compile("\\W");    String[] words = pattern.split("one@two#three:four$five");    for (String s : words) {      System.out.println("Split using Pattern.split(): " + s);    }     // using Matcher.replaceFirst() and replaceAll() methods    pattern = Pattern.compile("1*2");    matcher = pattern.matcher("11234512678");    System.out.println("Using replaceAll: " + matcher.replaceAll("_"));    System.out.println("Using replaceFirst: " + matcher.replaceFirst("_"));  } }

Since regular expressions are always related to strings, Java 1.4 extends the String class and provides a matches method to match pattern. The Pattern and Matcher classes are used inside the method to handle these things, but this obviously reduces the number of lines of code.

The Pattern class also has the matches method, which can match the regular expression with the string used as the parameter input and output the boolean result.

The following code matches the input string with the regular expression.

String str = "bbb";System.out.println("Using String matches method: "+str.matches(".bb"));System.out.println("Using Pattern matches method: "+Pattern.matches(".bb", str));

Therefore, if you only need to check whether the input String matches pattern, you can save time by calling the String matches method. You only need to use the pattern and Matches classes when you need to operate the input string or reuse Pattern.

Note that the pattern defined by the regular expression is applied from left to right. Once an original character is used in a match, it will not be used again.

For example, the regular "121" will only match the string "31212142121" twice, just like "_ 121____121 ″.
Regular Expression

Java Regular Expression metacharacters

There are two ways to use metacharacter in a regular expression like a common character.

Add a backslash (\) before the metacharacters (\)
Place metacharacters between \ Q (start reference) and \ E (end reference)
Regular Expression quantifiers

Quantifiers specify the occurrence times of character matching.

The quantifiers can be used with character classes and capturing group.

For example, [abc] + indicates that a, B, or c appears once or multiple times.

(Abc) + indicates that the capturing group "abc" appears once or multiple times. We will discuss capturing group soon.

Regular Expression capturing group

Capturing group is used to deal with multiple characters that appear as a whole. You can create a group by using. The part of the input string that matches the capturing group is saved in the memory and can be called by using Backreference.

You can use the matcher. groupCount method to obtain the number of capturing groups in a regular pattern. For example, (a) (bc) contains three capturing groups; (a) (bc), (a), and (bc ).

You can use Backreference in a regular expression and a backslash (\) to call the group number.

Capturing groups and Backreferences may be confusing, so we can use an example to understand them.

System.out.println(Pattern.matches("(\\w\\d)\\1", "a2a2")); //true  System.out.println(Pattern.matches("(\\w\\d)\\1", "a2b2")); //false  System.out.println(Pattern.matches("(AB)(B\\d)\\2\\1", "ABB2B2AB")); //true  System.out.println(Pattern.matches("(AB)(B\\d)\\2\\1", "ABB2B3AB")); //false

In the first example, the first capturing group is (\ w \ d ), obtain "a2" when matching the input string "a2a2" and save it to the memory. Therefore, \ 1 is a reference of "a2" and returns true. For the same reason, the second line of code prints false.

Try to understand the third and fourth lines of code. :)

Now let's take a look at some important methods in the Pattern and Matcher classes.

We can create a Pattern object with a flag. For example, Pattern. CASE_INSENSITIVE can be used for case-insensitive matching. The Pattern class also provides the split (String) method similar to the String class.

The toString () method of the Pattern class returns the regular expression string compiled into this pattern.

The Matcher class has the start () and end () index methods. They can display the exact position matched from the input string.

The Matcher class also provides the String operation methods replaceAll (String replacement) and replaceFirst (String replacement ).

Now let's look at how these functions are used in a simple java class.

package com.journaldev.util; import java.util.regex.Matcher;import java.util.regex.Pattern; public class RegexExamples {   public static void main(String[] args) {    // using pattern with flags    Pattern pattern = Pattern.compile("ab", Pattern.CASE_INSENSITIVE);    Matcher matcher = pattern.matcher("ABcabdAb");    // using Matcher find(), group(), start() and end() methods    while (matcher.find()) {      System.out.println("Found the text \"" + matcher.group()          + "\" starting at " + matcher.start()          + " index and ending at index " + matcher.end());    }     // using Pattern split() method    pattern = Pattern.compile("\\W");    String[] words = pattern.split("one@two#three:four$five");    for (String s : words) {      System.out.println("Split using Pattern.split(): " + s);    }     // using Matcher.replaceFirst() and replaceAll() methods    pattern = Pattern.compile("1*2");    matcher = pattern.matcher("11234512678");    System.out.println("Using replaceAll: " + matcher.replaceAll("_"));    System.out.println("Using replaceFirst: " + matcher.replaceFirst("_"));  } }

Output of the above program:

Found the text "AB" starting at 0 index and ending at index 2Found the text "ab" starting at 3 index and ending at index 5Found the text "Ab" starting at 6 index and ending at index 8Split using Pattern.split(): oneSplit using Pattern.split(): twoSplit using Pattern.split(): threeSplit using Pattern.split(): fourSplit using Pattern.split(): fiveUsing replaceAll: _345_678Using replaceFirst: _34512678

This is not a comprehensive Java Regular Expression learning tutorial, I hope to help you learn.

Articles you may be interested in:
  • Java Regular Expressions
  • JAVA Regular Expressions Pattern and Matcher
  • Use regular expressions in Java/Js to match Nested Html tags
  • Java Regular Expression learning summary and some small examples
  • Some common java Regular Expressions collected
  • Java uses regular expressions to extract () Content
  • Example of java regular expression to extract numbers
  • Java Regular Expression verification email and phone number example
  • Example of a java Regular Expression matching all URLs and link texts on a webpage
  • Java regular expression form verification tools (verification email, mobile phone number, QQ number, etc)

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.