Java regular expression 4 common functions

xiaoxiao2021-03-05  23

Regular expressions have a powerful feature on string processing, and Sun has added support to it in JDK1.4.

The following is simple to say its four common functions:

Inquire:

String str = "ABC EFG ABC";

String regex = "a | f"; // means A or F

Pattern P = Pattern.Compile (regex);

Matcher M = P.matcher (STR);

Boolean RS = m.find ();

If there is regex in the STR, then rs is true, otherwise it is Flase. If you want to ignore your case, you can write it.

Pattern P = Pattern.Compile (regex, pattern.case_insensitive);

extract:

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 execution result is Name.txt, and the extracted string is stored in M.Group (i), where i is the maximum value of 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 is a simple method:

String str = "xd :: abc :: cde";

String [] r = Str.Split ("::");

Replace (delete):

String regex = "a "; // means one or more A

Pattern P = Pattern.Compile (regex);

Matcher M = P.matcher ("Aabbced a ccdeaa);

String s = m.ReplaceAll ("a");

The result is "abbced a ccdea"

If you write into an empty string, you can reach the delete function, such as:

String s = m.ReplaceAll ("");

The result is "BBCED CCDE"

Attachment:

/ d equal to [0-9] number

/ D equal to [^ 0-9] non-number

/ S is equal to [/ T / N / X0B / F / R] blank font

/ S is equal to [^ / T / N / X0B / F / R] non-blank character

/ W is equal to [A-ZA-Z_0-9] number or English

/ W is equal to [^ a-za-z_0-9] non-numbers and English words

^ Indicates the beginning of each line

$ Indicates the end of each line

转载请注明原文地址:https://www.9cbs.com/read-38610.html

New Post(0)