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)