Java classic instance: Find the matched text, java classic instance

Source: Internet
Author: User

Java classic instance: Find the matched text, java classic instance

Import java. util. regex. matcher; import java. util. regex. pattern;/*** Created by Frank */public class REMatch {public static void main (String [] args) {String patt = "Q [^ u] \ d + \\. "; Pattern r = Pattern. compile (patt); String line = "Order QT300. Now! QT400. "; Matcher m = r. matcher (line); int I = 0; while (m. find () {// group (0) or group () returns the entire matched string (exact match); group (I) only one group System is returned. out. println (patt + "matches \" "+ m.Group(0) + "\" in \ "" + line + "\" "); System. out. println ("start:" + m. start () + "end:" + m. end ());}}}

Output:

Q[^u]\d+\. matches "QT300." in "Order QT300. Now! QT400."start:6 end:12Q[^u]\d+\. matches "QT400." in "Order QT300. Now! QT400."start:18 end:24

 

Import java. util. regex. matcher; import java. util. regex. pattern;/*** Created by Frank */public class REMatchTwoFields {public static void main (String [] args) {String inputLine = "Adams, John Quincy "; pattern r = Pattern. compile ("(. *),(. *) "); Matcher m = r. matcher (inputLine); if (! M. matches () {throw new IllegalArgumentException ("Bad Input");} // The entire original string for (int I = 0; I <m. groupCount () + 1; I ++) {System. out. println ("group" + I + ":" + m. group (I ));}}}

Output:

Group 0: Adams, John Quincy Group 1: Adams group 2: John Quincy

 

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.