Regular expressions Several common functions - query, extraction, replacement, segmentation Select BLOG from Shuqianlz

xiaoxiao2021-03-06  70

Regular expressions have strong features on string processing. Sun joins its four common functions in JDK1.4, which is simple to say below: Query: string str = "abc EFG ABC"; String Regex = "a | f"; // denotes a or f pattern p = pattern.Compile (regex); matcher m = p.matcher (STR); Boolean RS = M.Find (); if there is regex in Str, then RS is True, otherwise it is Flase. If you want to ignore your case when you look up, you can write to 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, the extracted string is stored in M.Group (i), where i maximum For M.GroupCount (); Split: 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 "; // represents one or more A pattern p = pattern.Compile (regex); matcher m = p.matcher (" Aabbced a ccdeaaa); string s = M.ReplaceAll ("a"); "ABBCED a ccdea" If written into an empty string, it can achieve the delete function, such as string s = m.replaceAll ("); result is" BBCED CCDE "attached: / D is equal to [0-9] digital / d equal to [^ 0-9] non-digital / S equal to [/ T / N / X0B / f / R] blank font / s equal to [^ / T / N / X0B / F / R] Non-blank character / w is equal to [A-ZA-Z_0-9] number or English word / W is equal to [^ a-za-z_0-9] non-numbers and English words ^ indicate the beginning of each line End of each line

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

New Post(0)