Java进阶——使用正则表达式检索、替换String中的特定字符和关于正则表达式的一切

引言

String这个对于程序原来说一定是最熟悉不过的,很多时候我们都习惯去使用String的原生方法去完成查找字符串、替换、删除,而正则表达式由于略显苦涩的语法常常被人忽略,其实很多时候使用正则表达式可以提高不少性能和节省资源。

一、正则表达式简述

正则表达式正则表达是Java中比较矛盾的知识点,因为使用起来可以很简单也可以相当地有难度,但是对于字符串操作来说应用得当则事半功倍,字符串查找,搜索,匹配,替换等等,正则表达式无所不能。而所谓正则表达式本质就是一个字符串(这个字符串按照一定的语法和规范被构造出来作为限定条件),其主要参与者——PatternMatcherPattern是Java正则表达式API中的主要入口,是程序语言中对这个特殊正则字符串的编译表示,需要使用正则表达式,第一步都是从构造Pattern 类开始,而Matcher是输入字符串进行解释和匹配操作的引擎,通过解释 Pattern 对 Character sequence 执行匹配操作(即Matcher负责完成字符串的查找、匹配、替换等操作。)

二、正则表达式基本语法

1、预留字符

限定符 说明
. 任意英文字母
\ 反斜杠, 单独的反斜杠做为转义字符,与其他特殊字符一起使用。如果想匹配反斜杠本身,需要转义。两个反斜杠实际匹配一个反斜杠n字符的8进制表示.n 在0至7之间取值
nn 字符的8进制表示.n 在0至7之间取值
mnn 字符的8进制表示. m 在0至3之间取值, n 在0至7之间取值
\xhh 字符的16进制表示.
\uhhhh 字符的16进制表示 0xhhhh. 对应unicode 编码字符
\t 缩进符.
\n 换行符 (unicode: ‘\u000A’)
\r 回车符 (unicode: ‘\u000D’)
\f 制表符 (unicode: ‘\u000C’)
\a 警报(铃声)字符 (unicode: ‘\u0007′)
\e 转义符 (unicode: ‘\u001B’)
\cx 控制符 x
\d 匹配任意数字 [0-9]
\D 匹配任意非数字 [^0-9]
\s 匹配任意空白符 (空格, 缩进, 换行,回车)
\S 匹配任意非空白符
\w 匹配任意单词
\W 匹配任意非单词

2、设置指定限定条件[](即“[]”表示的是中括符里的内容是条件)

限定符 说明
[a-z] 匹配小写a to z范围中任一个字符,又如[abc] 匹配 a, 或 b 或 c
[A-Z] 匹配大写A to Z范围中任一个字符
[a-zA-Z] 匹配小写a to z或大写A to Z范围中一个字符
[0-9] 匹配小写0 to 9范围中一个字符
[0-9a-z] 匹配小写0 to 9或a to z范围中一个字符
[0-9[a-z]] 匹配小写0 to 9或a to z范围中一个字符(交集)
[^abc] 匹配不是a,b,c 的字符,是否定匹配
[a-zA-Z] 匹配a 到 z ,A到Z 直接的字符,是范围匹配
[a-d[m-p]] 匹配a到d之间字符或 m到p之间字符,是并集匹配
[a-z&&[def]] 匹配 d, e, 或 f. 是交集匹配 (这里是在范围 a-z和字符def之间取交集).
[a-z&&[^bc]] 匹配a-z 之间所有字符,排除bc的字符。是减法匹配
[a-z&&[^m-p]] 匹配a-z 之间所有字符,排除m-p之间的字符是减法匹配

3、边界匹配

边界符 说明
^ 匹配行首
$ 匹配行尾
\b 匹配单词边界
\B 匹配非单词边界
\A 匹配文本开头
\G 匹配前一匹配项结尾
\Z 输入的结尾,仅用于最后的结束符(如果有的话)
\z 匹配文本结尾

4、逻辑操作符和量词表示

正则表达式支持少量的逻辑运算(与,或)。与操作是默认的,表达式 cmo,意味着c 与 m与o。 
或操作需要显示指定,用 | 表示。例如表达式 crazy|mo意味着crazy或 mo。

贪婪模式 饥饿模式 独占模式 说明
X? X?? X?+ 匹配0或1次,即出现X 0或者1次
X* X**? X*+ 匹配0或多次
X+ X+? X++ 匹配1或多次
X{n} X{n}? X{n}+ 匹配n次
X{n,} X{n,}? X{n,}+ 匹配最少n次
X{n, m} X{n, m}? X{n, m}+ 匹配最少n次,最多m次

三、正则表达式的应用

  • 编译正则表达式的字符串值构造对应的模式Pattern对象
  • 创建匹配给定输入与此模式的匹配器Matcher
  • 通过匹配器对象执行操作,匹配器对象的方法很丰富,互相组合使用更加强大(JDK在线API

1、去掉字符串中的空格和换行符

public static String getNonBlankStr(String str) {      
     if(str!=null && !"".equals(str)) {      
         Pattern pattern = Pattern.compile("\\s*|\t|\r|\n"); //去掉空格符合换行符     
         Matcher matcher = pattern.matcher(str);      
         String result = matcher.replaceAll("");      
         return result;      
     }else {      
         return str;      
     }           
 }   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2、去掉指定特殊字符

public   static   String StringFilter(String   str)   throws PatternSyntaxException {

    // String   regEx  =  "[^a-zA-Z0-9]"; // 只允许字母和数字
    // 清除掉所有特殊字符(除了~之外)
    String regEx="[`!@#$%^&*()+=|{}':;',//[//].<>/?!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
    Pattern pattern   =   Pattern.compile(regEx);
    Matcher matcher   =   pattern.matcher(str);
    return   matcher.replaceAll("").trim();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3、Pattern.matches()检查字符串中是否存在指定字符

String text    = "there are many hotels " +"by amap.the adrr: http://xxxx pattern.";
String pattern = ".*http://.*";
boolean matches = Pattern.matches(pattern, text);//true则存在
  • 1
  • 2
  • 3

4、Pattern.split()用正则表达式作为分隔符,把文本分割为String类型的数组

/**
* 结果:element =  grjk Text 
element =  wwwdsf 
element =  Many 
element =  egsdg r geg
*/
String text = "A reg grjk Text reg wwwdsf reg Many reg egsdg r geg";
String patternString = "reg";
Pattern pattern = Pattern.compile(patternString);
String[] split = pattern.split(text);
for(String element : split){
    System.out.println("element = " + element);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

5、Matcher 实例的find() + start() + end()寻找字符串中指定字符串出现的次数和起始和结束的索引位置

/**
*结果:found: 1 : 2 - 4
found: 2 : 5 - 7
found: 3 : 23 - 25
found: 4 : 70 - 72
*/
String text    ="This is the text which is to be searched " +"for occurrences of the word 'is'.";               
String patternString = "is";                
Pattern pattern = Pattern.compile(patternString);               
Matcher matcher = pattern.matcher(text);
int count = 0;
while(matcher.find()) {             
    count++;                
    System.out.println("found: " + count + " : "  + matcher.start() + " - " + matcher.end());               
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

6、Matcher 匹配指定格式的特殊字符串

        Pattern pattern = Pattern.compile("[0-9]*");//判断是否都是数字
        Matcher isNum = pattern.matcher("1123是数字");
        if(isNum.matches()) {
            System.out.println("全部是数字");
        } else {
            System.out.println("有汉字");
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

待续…

https://blog.csdn.net/crazymo_/article/details/67634590

版权声明:本文为博主原创文章,转载请注明链接Powered By cmo! https://blog.csdn.net/CrazyMo_/article/details/67634590

猜你喜欢

转载自blog.csdn.net/heyics/article/details/79833430