Java-11.4 regular expression (1)-perceptual knowledge
In this section, let's take a look at the regular expression.
A regular expression describes a string in some form.
Note: in java, the backslash of the regular expression must be \. If it is a normal backslash, it must be described.
There are several regular expressions in the string: matches, split, and replaceAll.
1. matches Method
The following is just an example to let everyone feel that the expression is in progress.
package com.ray.ch11;public class Test {public static void main(String[] args) {System.out.println(-21.matches(-?\d+));System.out.println(-21.matches(-?\d));System.out.println(+21.matches(\+?\d+));System.out.println(+21.matches((-|\+)?\d+));}}
Output:
True
False
True
True
Explanation:
-? Indicates a number with a negative number.
D indicates the integer of each digit.
D + indicates the integer of multiple digits.
| Represents or
\ + Indicates the plus sign. In a regular expression, the plus sign must be preceded by a backslash.
2. split Method
Split can accept strings or regular expressions.
package com.ray.ch11;import java.util.Arrays;public class Test {public static void main(String[] args) {System.out.println(Arrays.toString(-21a333adg.split(-?\d)));System.out.println(Arrays.toString(-21a333adg.split(\d)));System.out.println(Arrays.toString(-21a333adg.split(\d\d)));System.out.println(Arrays.toString(-21a333adg.split(-\d\d)));System.out.println(Arrays.toString(-21a333adg.split(a)));System.out.println(Arrays.toString(-21a333adg.split(d)));System.out.println(Arrays.toString(-21a333adg.split(g)));}}
Output:
[, A, adg]
[-, A, adg]
[-, A, 3adg]
[, A333adg]
[-21,333, dg]
[-21a333a, g]
[-21a333ad]
3. replaceAll Method
ReplaceAll can accept strings or regular expressions.
package com.ray.ch11;public class Test {public static void main(String[] args) {System.out.println(-21a333adg.replaceAll(-?\d, 0));System.out.println(-21a333adg.replaceAll(\d, 0));System.out.println(-21a333adg.replaceAll(\d\d, 0));System.out.println(-21a333adg.replaceAll(-\d\d, 0));System.out.println(-21a333adg.replaceAll(a, 0));System.out.println(-21a333adg.replaceAll(d, 0));System.out.println(-21a333adg.replaceAll(g, 0));}}
Output:
00a000adg
-00a000adg
-0a03adg
0a333adg
-2103330dg
-21a333a0g
-21a333ad0
The first four of the above methods use regular expressions, and the last three are simple strings accepted.
Summary: This chapter provides several examples to give you a perceptual knowledge of regular expressions and shows three methods in strings that can accept regular expressions.