java正则表达式
Posted qq1312583369
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java正则表达式相关的知识,希望对你有一定的参考价值。
字符 x 字符 x。举例:‘a‘表示字符a \\ 反斜线字符。 \n 新行(换行)符 (‘\u000A‘) \r 回车符 (‘\u000D‘) 字符类 [abc] a、b 或 c(简单类) [^abc] 任何字符,除了 a、b 或 c(否定) [a-zA-Z] a到 z 或 A到 Z,两头的字母包括在内(范围) [0-9] 0到9的字符都包括 预定义字符类 . 任何字符。我的就是.字符本身,怎么表示呢? \. \d 数字:[0-9] \D 非数字:[^\d]/[^0-9] \w 单词字符:[a-zA-Z_0-9] \W 非字符[^\w] 边界匹配器 ^ 行的开头 $ 行的结尾 \b 单词边界, 就是不是单词字符的地方。 Greedy 数量词 X? X,一次或一次也没有 X* X,零次或多次 X+ X,一次或多次 Xn X,恰好 n 次 Xn, X,至少 n 次 Xn,m X,至少 n 次,但是不超过 m 次 运算符 XY X后跟 Y X|Y X 或 Y (X) X,作为捕获组
String类中的三个基本操作使用正则:
匹配:matches()
切割: split()
替换: replaceAll()
1匹配验证-验证Email是否正确
public static void main(String[] args) // 要验证的字符串 String str = "[email protected]"; // 邮箱验证规则 String regEx = "[a-zA-Z_]1,[0-9]0,@(([a-zA-z0-9]-*)1,\\.)1,3[a-zA-z\\-]1,"; // 编译正则表达式 Pattern pattern = Pattern.compile(regEx); // 忽略大小写的写法 // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(str); // 字符串是否与正则表达式相匹配 boolean rs = matcher.matches(); System.out.println(rs);
2在字符串中查询字符或者字符串
public static void main(String[] args) // 要验证的字符串 String str = "baike.xsoftlab.net"; // 正则表达式规则 String regEx = "baike.*"; // 编译正则表达式 Pattern pattern = Pattern.compile(regEx); // 忽略大小写的写法 // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(str); // 查找字符串中是否有匹配正则表达式的字符/字符串 boolean rs = matcher.find(); System.out.println(rs);
3常用正则表达式
规则 | 正则表达式语法 |
一个或多个汉字 | ^[\u0391-\uFFE5]+$ |
邮政编码 | ^[1-9]\d5$ |
QQ号码 | ^[1-9]\d4,10$ |
邮箱 | ^[a-zA-Z_]1,[0-9]0,@(([a-zA-z0-9]-*)1,\.)1,3[a-zA-z\-]1,$ |
用户名(字母开头 + 数字/字母/下划线) | ^[A-Za-z][A-Za-z1-9_-]+$ |
手机号码 | ^1[3|4|5|8][0-9]\d8$ |
URL | ^((http|https)://)?([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$ |
18位身份证号 | ^(\d6)(18|19|20)?(\d2)([01]\d)([0123]\d)(\d3)(\d|X|x)?$ |
以上是关于java正则表达式的主要内容,如果未能解决你的问题,请参考以下文章