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

CharacterMatchesCharacterMatches
\dany digit\Dany nondigit

\w

any word character\Wany nonword character
\sany white-space character\Sany non-whitespace character

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

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

… etc。

 

Quantifiers

QuantifierMatches
*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 }

 

转载于:https://www.cnblogs.com/RDaneelOlivaw/p/11511354.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值