---
title: "Regex 字符组"
author: "roway"
date: "2012-10-31T16:28:00Z"
tags: []
categories: ["编程语言"]
slug: "regex"
draft: false
lastmod: "2012-11-13T13:38:10Z"
id: 1722886
url: "https://roway.iteye.com/blog/1722886"
---

1.字符组Character Class  
a.正则表达式的最基本结构之一。  
b.作用：规定某个位置能够出现的字符。  
c.形式：以【\[...]】给出，在方括号内列出允许出现的字符。  
2.以连字符‘-’表示范围  
\[0123456789]=\[0-9]  
\[0-789]=\[0-9]  
\[0123456789abcdef]=\[0-9a-f]  
3.关于连字符的注意事项  
注意：在字符组内部，只有当连字符出现在两个字符之间时，才能表示字符的范围；  
如果出现在字符组的开头，则只能表示单个字符‘-’  
4.排除型字符组  
a.作用：规定某个位置不容许出现的字符  
b.形式：以\[^...]给出，在方括号内列出不容许出现的字符。

c.排除型字符组仍然必须匹配一个字符。------&gt;重点！！！

 

```
/**
 * ^排除型字符组仍然必须匹配一个字符
 * */
public class NegativeCharacterClassMind {

	public static void main(String[] args) {
		String[] strings = new String[] { "case", "casa", "caso", "cas" };

		String regex = "cas[^e]";//排除型字符组仍然必须匹配一个字符

		for (String s : strings) {
			if (regexMatch(s, regex)) {
				System.out.println("\"" + s + "\" can be matched with regex \""
						+ regex + "\"");
			} else {
				System.out.println("\"" + s
						+ "\" can not be matched with regex \"" + regex + "\"");
			}
		}

	}

	public static boolean regexMatch(String s, String regex) {
		return s.matches(regex);
	}

}
```

 

e.^在\[]里面的第一个字符的意思是取反  
^其他代表一行的开头。  
5.字符组简记法  
对于常用的字符组，正则表达式提供了相应的简记法，方便地表示它们。  
\\d=\[0-9]  
\\D=\[^0-9]  
\\w=\[0-9a-zA-Z\_]  
\\W=\[^0-9a-zA-Z\_]  
\\s=匹配空白字符(回车、换行、制表、空格)  
\\S=匹配非空白字符  
6.特殊的简记法：点号  
a.点号.是一个特殊的字符组间记法，它可以匹配几乎所有字符  
b.\\.匹配点号本身  
c.在字符组内部，\[.]也只能匹配点号本身

注意：点号不能匹配换行符。(默认是匹配模式是点号是可以匹配换行符的)

 

```
/**
 * 注意：点号不能匹配换行符。
 * */
public class DotMatchMind {
	public static void main(String[] args) {
		
		String dot = ".";
		
		String lineFeed = "\n";
		
		if(regexMatch(lineFeed, dot)) {
			System.out.println("Dot can match LineFeed");
		}
		else {
			System.out.println("Dot can not match LineFeed");
		}
		

	}
	
	public static boolean regexMatch(String s, String regex) {
		return s.matches(regex);
	}

}
```