Java: Regular Expressions

[]只匹配单个字符

[枚举若干字符]:范围为所列字符。E.g. [aeiou] == a,e,i,o,u都可匹配。

[起点-终点]:范围为给定区间。

E.g.

[A-Y] == 大写字母A~Y都可匹配;

[A-Za-z] == 所有大写字母和小写字母都可匹配;

[A-z] == 大写A到小写z之间所有值,包括[,|等符号。

 

()组合

|:操作符左右任取其一。E.g. Hi (John|Jane)==匹配Hi John或Hi Jane。

 

Predefined Character Classes

Character Matches Character Matches
\d any digit \D any nondigit

\w

any word character \W any nonword character
\s any white-space character \S any non-whitespace character

\\d == 1或以上任意长度的数字串;(加在\d前的第一个\用于取消第二个\的转义)

\\s == 1或以上任意长度的空格串;

… etc。

 

Quantifiers

Quantifier Matches
* Matches zero or more occurrences of the pattern.
+ Matches one or more occurrences of the pattern.
? Matches zero or one occurrences of the pattern.
{n} Matches exactly n occurrences.
{n,} Matches at least n occurrences.
{n,m} Matches between n and m (inclusive) occurrences.

 

*:操作符前面紧接的pattern出现任意多次,可匹配空串。E.g. A, AAA都可匹配A*。

+:操作符前面紧接的pattern出现1或以上任意多次,不能匹配空串。E.g. A, AAA都可匹配A+,空串不能。

All quantifiers are greedy – will match as many occurrences as possible as long as the match is still successful.

But an ? following the quantifier can make it lazy  (reluctant) -- it then will match as few occurrences as possible.

 

e.g.

 1 public class ValidateInput {
 2     
 3     public static boolean validateFirstName(String firstName) {
 4         return firstName.matches("[A-Z][a-zA-Z]*");
 5     }// Jane
 6     
 7     public static boolean validateLastName(String lastName) {
 8         return lastName.matches("[a-zA-z]+(['-][a-zA-Z]+)*");
 9     }// Doe
10     
11     public static boolean validateAddress(String address) {
12         return address.matches("\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
13     } //10 Boradyway or 10 Main Street
14     
15     public static boolean validateCity(String city) {
16         return city.matches("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
17     } //Waltham or West Newton
18     
19     public static boolean validateState(String state) {
20         return state.matches("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
21     } //SS
22     
23     public static boolean validateZip(String zip) {
24         return zip.matches("\\d{5}");
25     } //12345
26     
27     public static boolean validatePhone(String phone) {
28         return phone.matches("[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}");
29     } //123-456-7890
30 
31 }

 

posted @ 2019-09-16 10:34  丹尼尔奥利瓦  阅读(214)  评论(0编辑  收藏  举报