Let's take a look at the regular expressions in this chapter.
A regular expression is a form of describing a string.
Note: In Java, the backslash of the regular expression needs "\ \" to describe, if it is a normal backslash, need "\\\\" to describe.
There are several ways to use regular methods in a string, namely matches, split, and ReplaceAll
1.matches method
Here are just a few examples to make you feel like you're expressing yourself.
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
Explain:
-Represents a number with a minus sign
\d represents a single-digit integer
\d+ An integer that represents a multi-digit number
| indicates or
\\+ means plus, in regular expressions, the plus sign needs to precede the backslash
2.split method
Split can accept a string, or it can accept a regular expression.
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 a string, or it can accept a regular expression.
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 previous four methods use regular expressions, followed by three simply accepting strings.
Summary: This chapter focuses on a few examples to give you a perceptual understanding of regular expressions and to show the three ways in which you can accept a regular expression.
This chapter is here, thank you.
-----------------------------------
Directory
Understanding java-11.4 Regular Expressions from the beginning (1)-Perceptual cognition