您的位置:首页 > 编程语言 > Java开发

Java基础_正则表达式常用

2012-12-29 20:48 519 查看
import java.util.regex.Pattern;

public class RegularTest1 {

public static void main(String[] args) {

// Pattern中

System.out.println("a".matches("."));//true

System.out.println(Pattern.matches("aa", "aa"));//true

System.out.println("aaaa".matches("a*"));//true

System.out.println(Pattern.matches("a+", "aaaa"));//true

System.out.println("".matches("a*"));//true

System.out.println(Pattern.matches("a?", "a"));//true

System.out.println("214523145234523".matches("\\d{3,100}"));//true

System.out.println(Pattern.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}", "192.168.0.1"));//true

System.out.println("192".matches("[0-2][0-9][0-9]"));//true

System.out.println("-----------Pattern--------------");

// 转义字符

/*

\\ 反斜线字符

\t 制表符 ('\u0009')

\n 新行(换行)符 ('\u000A')

\r 回车符 ('\u000D')

\f 换页符 ('\u000C')

\a 报警 (bell) 符 ('\u0007')

\e 转义符 ('\u001B')

*/

System.out.println(" ".matches("\\s") && "\n".matches("\\s") && "\t".matches("\\s") && "\f".matches("\\s") && "\r".matches("\\s"));//true

System.out.println("\\".matches("\\\\"));//true

System.out.println("-----------字符 --------------");

// 范围

/*

[abc] a、b 或 c(简单类)

[^abc] 任何字符,除了 a、b 或 c(否定)

[a-zA-Z] a 到 z 或 A 到 Z,两头的字母包括在内(范围)

[a-d[m-p]] a 到 d 或 m 到 p:[a-dm-p](并集)

[a-z&&[def]] d、e 或 f(交集)

[a-z&&[^bc]] a 到 z,除了 b 和 c:[ad-z](减去)

[a-z&&[^m-p]] a 到 z,而非 m 到 p:[a-lq-z](减去)

*/

System.out.println("a".matches("[abc]"));//true

System.out.println("a".matches("[^abc]"));//false

System.out.println("A".matches("[a-zA-Z]"));//true

System.out.println("A".matches("[a-z]|[A-Z]"));//true

System.out.println("A".matches("[a-z[A-Z]]"));//true

System.out.println("R".matches("[A-Z&&[RFG]]"));//true

System.out.println("----------范围---------------");

// 预定义字符类

/*

. 任何字符(与行结束符可能匹配也可能不匹配)

\d 数字:[0-9]

\D 非数字: [^0-9]

\s 空白字符:[ \t\n\x0B\f\r]

\S 非空白字符:[^\s]

\w 单词字符:[a-zA-Z_0-9]

\W 非单词字符:[^\w]

*/

// 数量词

/*

X? X,一次或一次也没有

X* X,零次或多次

X+ X,一次或多次

X{n} X,恰好 n 次

X{n,} X,至少 n 次

X{n,m} X,至少 n 次,但是不超过 m 次

*/

System.out.println(" \n\r\t".matches("\\s{4}"));

System.out.println(" ".matches("\\S"));

System.out.println("a_8".matches("\\w{3}"));

System.out.println("abc888&^%".matches("[a-z]{1,3}\\d+[&^#%]+"));

// System.out.println("\\".matches("\\"));//会出现编译错误

System.out.println(Pattern.matches("\\\\", "\\"));

System.out.println("-------------数量词---------------------");

// 边界匹配

/*

* 边界匹配器

^ 行的开头

$ 行的结尾

\b 单词边界

\B 非单词边界

\A 输入的开头

\G 上一个匹配的结尾

\Z 输入的结尾,仅用于最后的结束符(如果有的话)

\z 输入的结尾

*/

System.out.println("hello sir".matches("^h.*"));//true

System.out.println("hello sir".matches(".*ir$"));//true

System.out.println("hello sir".matches("^h[a-z]{1,3}o\\b.*"));//true

System.out.println("hellosir".matches("^h[a-z]{1,3}o\\b.*"));//false

//空行

System.out.println("-------------边界---------------------");

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: