正则表达式的总结
JasonDev324

括号含义

  • {}一般用来表示匹配的长度
  • []匹配的字符范围
  • ()提取匹配的字符串

基本字符

(一个元字符替代一个字符 例如 \w 可以表示 2或者s或者’_’)

‘.’ 表示匹配除了换行符之外的任何字符
‘*’ 表示匹配除了换行符之外任意数量的字符

示例 - \b使用

含义 - 字母的开始或者结束

需求 - Erintrus后面有PROG
\bErintrus\b.*\bProg\b

需求 - 限制输入只能为Erintrus
\bErintrus\b

示例 - 转义字符需要加”/“

使用 - 匹配 ‘.’ 和’*’的话,就必须加转义字符

需求 - 匹配erintrus.github.io 和c:/erintrus
erintrus.github.com 和c://erintrus


示例 - 字符的开始、结束

‘^’表示匹配字符串的开始(在字母前,若放在非字母前面表示非)
‘$’表示匹配字符串的结束

需求 - 输入5-12位QQ号码
^\d{5,12}$


匹配数字 \d

含义 - \d表示匹配0-9的任意字符(即数字)

需求 - 区号的电话 如 010-2254789

A. \d\d\d-\d\d\d\d\d\d\d\d
B. \d{2}-\d{8} {n}表示前面连续重复匹配N次
\d+ 跟\d* 的区别
前者匹配1-n个数字,后者匹配0-n个数字


空格\s

\s匹配任意的空白符,包括空格,制表符(Tab),换行符,中文全角空格


匹配字母或数字或下划线\w

含义 - \w匹配字母或数字或下划线(可以理解为表示字母)

需求 - 匹配以a开头的单词
\ba\w*\b (因为\b里面必须是单词,所以这里\w不会表示下划线或者数字)


限定符

含义 - 用于限定某个字符重复次数

示例 - 上面的的 \d+ 表示匹配1-n个数字

即\d+ 可以表示成 2 或者 2356

示例 - 只允许输入英文、数字以及下划线

涉及相关类包括Pattern、Matcher

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
etCommonText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

}

@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String editable = etCommonText.getText().toString();
String str = stringFilter(editable);
if (!editable.equals(str)) {
etCommonText.setText(str);
//设置新的光标所在位置
etCommonText.setSelection(str.length());
}
}

@Override
public void afterTextChanged(Editable editable) {

}
});
1
2
3
4
5
6
7
public static String stringFilter(String str) throws PatternSyntaxException {
// 只允许字母和数字
String regEx = "[^a-zA-Z0-9_]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
Powered by Hexo & Theme Keep
Total words 22k Unique Visitor Page View