The use of regular expressions for string checking, interception is very convenient, the project development of flexible using regular expressions can make your code simple and elegant and easy to error. In practical applications, the following knowledge can be used to deal with the vast majority of development scenarios.
1, the string begins to end match: ^$.
^abc$ exactly matches the string ABC.
2, specific type of character matching: digital \d, digital letter underline \w, Space \s, any character.
3. Repeat match: repeat 0 or 1 times, repeat 1 times and above +, repeat 0 times and above *, repeat M to n times {m,n}, repeat M more than {m,}.
\d+ identifies a string consisting of one or more digits, such as 0, 10,110.
4, single character or [],|.
[AB] indicates that a or b,a|b represents a or B.
5, String, or (|).
(AB|BC) denotes ab or BC.
6, not [^].
[^a] Represents a character that is not A; [^ab] represents a character that is not a and is not a B; [^ab]+ represents one or more characters, and each character is not a or B.
In Java, string.matches (regex) is used for string regular expression validation, String.replaceall () for regular expression substitution, and pattern,matcher for regular expression matching, lookup, substitution, and a series of operations. Here is the code example:
Package Com.coshaho.learn.reg;import Java.util.regex.matcher;import Java.util.regex.pattern;public class RegexTest { public static void Main (string[] args) {//repeating String regex = "^\\s*\\d+{1,3}\\w+." $"; String str = "110hkx_ @"; System.out.println (Str.matches (regex));//character or regex = "^[abc]$"; Equivalent to ^a|b|c$str = "B"; System.out.println (Str.matches (regex));//string or regex = "^ (AB|CD) $"; str = "AB"; System.out.println (Str.matches (regex));//non-regex = "^[^abc]$"; str = "D"; System.out.println (Str.matches (regex)); regex = "\\[([^\\[\\]]+) \\]\\.\\[([^\\[\\]]+) \ \]"; str = "[device]." [CPU] + [interface]. [Tranffic] >= 2 "; Pattern pattern = pattern.compile (regex); Matcher Matcher = Pattern.matcher (str), while (Matcher.find ()) {System.out.println (Matcher.group ()); if (2 = = Matcher.groupcount ()) {System.out.println (Matcher.group (1)); System.out.println (Matcher.group (2));}} Regex = "\\d+"; str = "ABC123DEF456HIJK789XYZ"; System.out.println (Str.replaceall (Regex, ""));}} /** output value Truetruetruetrue[device]. [Cpu]devicecpu[interfaCE]. [Tranffic]interfacetranfficabc def Hijk xyz**/
Java Regular Expressions use the