Java Support for regular expressions (i)

Source: Internet
Author: User

Java support for regular expressions is mainly embodied in the string, Pattern, Matcher, and scanner classes.

1.Pattern, Matcher

Let's look at an example of using regular expressions with the pattern and Matcher classes.

 Public classPatterntest { Public Static voidmain (string [] args) {string teststring= "ABCABCABCDEFABC"; String [] Regexs=NewString []{"abc+", "(ABC) +", "(ABC) {2,}"};  for(String regex:regexs) {Pattern P=pattern.compile (regex); Matcher m=P.matcher (teststring); System.out.println ("Test regex:" +regex);  while(M.find ()) {System.out.println ("Match" + m.group () + "at position" + m.start () + "-" + (M.end ()-1)); }        }    }    }

The result of the operation is:

Test regex:abc+0-23-56-812-14test regex: (ABC)+0-8  12-14Test regex: (ABC) {20-8

The meanings of several regular expressions are explained first:

abc+: Matches ABC or ABCC or ABCCC.

(ABC) +: According to the principle of greed, match 1 or more consecutive ABC, matching the longest string.

(ABC) {2,}:ABC appears at least 2 times, matches abcabc or ABCABCABC, and so on.

  

Java Support for regular expressions (i)

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.