Java Regular Expressions 4 common functions

Source: Internet
Author: User
Regular regular expressions have a powerful function in string processing, and sun has added support for it in jdk1.4

Here's a simple list of 4 common features:

Inquire:

String str= "ABC efg ABC";

String regex= "A|f"; Represents a or F

Pattern P=pattern.compile (regEx);

Matcher M=p.matcher (str);

Boolean rs=m.find ();

If there is a regex in Str, then RS is true, otherwise it is flase. If you want to ignore case when looking, you can write pattern p=pattern.compile (regex,pattern.case_insensitive);

Extraction:
String regex= ". +\\\\ (. +) $";

String str= "C:\\dir1\\dir2\\name.txt";

Pattern P=pattern.compile (regEx);

Matcher M=p.matcher (str);

Boolean rs=m.find ();

for (int i=1;i<=m.groupcount (); i++) {

System.out.println (M.group (i));

}

The above results are name.txt, and the extracted strings are stored in m.group (i), where I maximum is m.groupcount ();

Segmentation:

String regex= "::";

Pattern P=pattern.compile (regEx);

String[] R=p.split ("XD::ABC::CDE");

After execution, R is {"XD", "abc", "CDE"}, in fact, there are simple ways to split:

String str= "XD::ABC::CDE";

String[] R=str.split ("::");

Replace (delete):

String regex= "A +"; Represents one or more a

Pattern P=pattern.compile (regEx);

Matcher M=p.matcher ("aaabbced a Ccdeaa");

String S=m.replaceall ("A");

The result is "abbced A Ccdea"

If you write an empty string, you can achieve the deletion function, for example:

String S=m.replaceall ("");

The result is "bbced ccde"

Report:

\d equal to [0-9] numbers
\d is equal to [^0-9] not digital
\s is equal to [\t\n\x0b\f\r] blank character
\s is equal to [^ \t\n\x0b\f\r] non-blank character
\w is equal to [a-za-z_0-9] numbers or English characters.
\w is equal to [^a-za-z_0-9] non-numerals and English characters

^ represents the beginning of each line
$ indicates the end of each line


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.