java正则表达式

来源:互联网 发布:用java打印等腰三角形 编辑:程序博客网 时间:2024/06/07 03:46

java正则表达式

import java.util.regex.Matcher;import java.util.regex.Pattern;public class TestRegExp {public static void main(String[] args) {String myText = "this is my 1st 2st life";String myRegex = "(\\d+\\w+)";Pattern p = Pattern.compile(myRegex);Matcher m = p.matcher(myText);/*if(m.find()){String matchText = m.group();int matchFrom = m.start();int matchEnd = m.end();System.out.println(matchText);System.out.println(matchFrom);System.out.println(matchEnd);}else{System.out.println("match failed");}*/System.out.println("================split================");while(m.find()){System.out.println(m.group());System.out.println(m.start());System.out.println(m.end());}System.out.println("================split================");System.out.println("".matches(".+"));System.out.println("12345".matches(".{3,5}"));System.out.println("123".matches("\\d{3,}"));System.out.println("aaaaaAAA".matches(".{0,5}"));System.out.println("================split================");if(Pattern.compile(myRegex).matcher(myText).find()){System.out.println("ok");}else{System.out.println("no");}System.out.println("================split================");System.out.println(myText);System.out.println(Pattern.compile(myRegex).matcher(myText).replaceAll("$1ABCDEFG"));System.out.println(Pattern.compile(myRegex).matcher(myText).replaceAll(""));System.out.println(Pattern.compile("\\s\\d+:\\d+:\\d+$").matcher("2016-6-9 09:07:44").replaceAll(""));System.out.println(Pattern.compile("\\s\\d+:\\d+:\\d+$").matcher("2016-6-9").replaceAll(""));System.out.println(Pattern.compile("(\\d+):(\\d+):(\\d+)$").matcher("2016-6-9 09:07:44").replaceAll("$1时$2分$3秒"));}}

运行结果:
================split================1st11142st1518================split================falsetruetruefalse================split================ok================split================this is my 1st 2st lifethis is my 1stABCDEFG 2stABCDEFG lifethis is my   life2016-6-92016-6-92016-6-9 09时07分44秒



1 0
原创粉丝点击