正则表达式

2019-12-27  本文已影响0人  郑海鹏

这是一篇很久之前记录的笔记,最近用到的比较多,索性发出来。
如果遇到不知道怎么写的正则,可以在评论中发出来,持续更新。

1. 限制开头(^) 与限制结尾($)

2. 范围限制([])

3. 反向范围限制([^])

4. 出现次数的限制(*, +, ?)

5. 指定出现次数({})

6. 转义字符

String reg = "\\d";
boolean isMatch = Pattern.matches(reg, "5");  
// isMatch == true;
String reg = "\\D";
boolean isMatch = Pattern.matches(reg, "5");  
// isMatch == false;
String reg = "\\w*";
boolean isMatch = Pattern.matches(reg, "aB_0"); 
// isMatch == true;
String reg = "\\W*";
boolean isMatch = Pattern.matches(reg, "++++"); 
// isMatch == true;
String reg = "\\.";
boolean isMatch = Pattern.matches(reg, "."); 
// isMatch == true;
String reg = "\\\\";
boolean isMatch = Pattern.matches(reg, "\\"); 
// isMatch == true;

7. 或者(|) 组合 (())

8. 实例

8.1 身份证号

分析:

String reg = "(\\d|X){15}|(\\d|X){18}";
boolean isMatch = Pattern.matches(reg, "140202199204055528"); 
// isMatch == true;

8.2 邮箱

分析:

String reg = "(\\w)+(\\.\\w+)*@(\\w)+(\\.\\w+)*";
boolean isMatch = Pattern.matches(reg, "284967632@qq.com"); 
// isMatch == true;

8.3 是否由指定字符组成

判断是否由指定数字组成,实际是在判断以这些字符开始且以这些字符结束,用 ^(想要的字符)+$ 即可。
例如判断是否由 数字和'+'、'-' 符号组成:

// JavaScript
var isValid = /^([0-9]|\+|\-)+$/.test(submitter);

8.4 判断是否包含Emoji

// JavaScript
var hasEmoji = /(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff])/.test(string);

8.5 不包含指定字符

不包含 abc 和 def。

^(?!.*(abc|def)).*$

8.5 不包含指定字符且包含指定字符

不包含 abc 并且 包含 def。
^((?!abc).)def((?!abc).)$

上一篇 下一篇

猜你喜欢

热点阅读