正则表达式关键和一些Java中的方法说明

正则表达式

*零次或多次
+一次或多次
\s 一个或多个空格
\d+一个或多个数字
\. .    ()? 括号内可选

Pattern Matcher PatternSyntaxException

replaceFirst 和replaceAll 区别
replaceFirst 替换首次匹配,replaceAll 替换所有匹配。

String word="cat";
String string = "cat cat cat cattie cat";
findWord(string,word);

matches 和 looking at 区别
matches 要求整个序列都匹配,而lookingAt 不要求。
lookingAt 方法虽然不需要整句都匹配,但是需要从第一个字符开始匹配。

String REGEX2 = "foo";               
String INPUT1 = "fooooooooooooooooo";               
String INPUT2 = "ooooofoooooooooooo";               
Pattern pattern;               
Matcher matcher;               
Matcher matcher2;               
pattern = Pattern.compile(REGEX2);               
matcher = pattern.matcher(INPUT1);               
matcher2 = pattern.matcher(INPUT2);   
System.out.println("Current REGEX is: "+REGEX2);               
System.out.println("Current INPUT is: "+INPUT1);               
System.out.println("Current INPUT2 is: "+INPUT2);                     
System.out.println("lookingAt(): "+matcher.lookingAt());               
System.out.println("matches(): "+matcher.matches());               
System.out.println("lookingAt(): "+matcher2.lookingAt());

replaceFirst 和replaceAll 区别
replaceFirst 替换首次匹配,replaceAll 替换所有匹配。

String REGEX = "dog";                 
String INPUT = "The dog says meow. " +"All dogs say meow.";                 String REPLACE = "cat";     
Pattern p = Pattern.compile(REGEX);                 
// get a matcher object                 
Matcher m = p.matcher(INPUT);                 
INPUT = m.replaceAll(REPLACE);                 
System.out.println(INPUT);               
appendReplacement 和 appendTail 方法
String REGEX = "a*b";                
String INPUT = "aabfooaabfooabfoobkkk";                
String REPLACE = "-";    
Pattern p = Pattern.compile(REGEX);            
// 获取 matcher 对象                
Matcher m = p.matcher(INPUT);                
StringBuffer sb = new StringBuffer();                
while(m.find()){                    
    m.appendReplacement(sb,REPLACE);                
}                
m.appendTail(sb);                
System.out.println(sb.toString());                
System.out.println();        
String str3 = "account=? and uu =? or n=?";        
System.out.println("多个分隔符返回值 :" );        
for (String retval: str3.split("and|or")){        
    System.out.println(retval);        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值