正则表达式必须牢记的几个元字符详解(java使用实例)

来源:互联网 发布:企业软件上线时刻表 编辑:程序博客网 时间:2024/06/05 09:12

正则表达式元字符

1、常用元字符

.

表示除了换行符之外任意一个字符

\s

空格字符(空格键、tab、换行、回车)

\S

非空格字符([^\s]

\d

一个数字,(相当于[0-9]

\D

一个非数字的字符,(相当于[^0-9]

\w

一个单次字符(word character)(相当于[a-zA-Z0-9]还有下划线)

^

一行的开始

$

一行的结尾

\b

一个单词的边界

\B

一个非单词的边界

[]

匹配方括号内的一个字符,例如:[abc]表示字符a,b,c中的任意一个(与a|b|c相同)

2、表示次数的元字符

*

重复零次或更多次

例如:a*匹配零个或者多个a

+

重复一次或更多次

例如:a+匹配一个或者多个a

?

重复零次或一次

例如:a?匹配零个或者一个a

{n}

重复n

例如:a{4}匹配4a

{n,}

重复n次或更多次

例如:a{4,}匹配至少4a

{n,m}

重复nm

例如:a{4,10}匹配4-10a

3、正则表达式定位符

^

^hell

定位符规定匹配模式必须出现在目标字符串开头

hellohellboy

$

ar$

定位符规定匹配模式必须出现在目标字符串结尾

carbar

\b

\bbomman\b

定位符规定匹配模式必须出现在目标字符串开头或结尾两个边界之一

bombhuman/woman

\B

\Bjava\B

定位符规定匹配模式必须出现在目标字符串开头和结尾两边界之内

ForjavaEJB

 

4、常用正则表达式

1、中文字符的匹配

正则表达式支持Unicode码,汉字范围可使用Unicode来表示

·[\u4E00-\u9FA5]汉字

·[\uFE30-\uFFA0]全角字符

·[^\x00-\xff]匹配双字节字符(包括汉字在内)

5、代码示例

/**
 * 
 */
package com.csdn.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexUtil {

/**
* Description:匹配第一条结果,dealStr目标字符串,regexStr正则表达式字符串,n目标字符串在正则表达式字符串的位置

* @author earn
* @date 2016年5月16日
*/
public static String getFirstString(String dealStr, String regexStr, int n) {
if (dealStr == null || regexStr == null || n < 1) {
return "";
}
Pattern pattern = Pattern.compile(regexStr, Pattern.CASE_INSENSITIVE
| Pattern.DOTALL);
Matcher matcher = pattern.matcher(dealStr);
while (matcher.find()) {
return matcher.group(n).trim();
}
return "";
}

/**
* Description:匹配所有结果,结果组装成数组放入list中

* @author earn
* @date 2016年5月16日
*/
public static List<String> getList(String dealStr, String regexStr, int n) {
List<String> list = new ArrayList<String>();
if (dealStr == null || regexStr == null || n < 1) {
return list;
}
Pattern pattern = Pattern.compile(regexStr, Pattern.CASE_INSENSITIVE
| Pattern.DOTALL);
Matcher matcher = pattern.matcher(dealStr);
while (matcher.find()) {
list.add(matcher.group(n).trim());
}
return list;
}

/**
* Description:匹配多个信息的所有结果,组装成数组放入list中

* @author earn
* @date 2016年5月16日
*/
public static List<String[]> getList(String dealStr, String regexStr,
int[] array) {
List<String[]> list = new ArrayList<String[]>();
if (dealStr == null || regexStr == null || array == null) {
return list;
}
for (int i = 0; i < array.length; i++) {
if (array[i] < 1) {
return list;
}
}
Pattern pattern = Pattern.compile(regexStr, Pattern.CASE_INSENSITIVE
| Pattern.DOTALL);
Matcher matcher = pattern.matcher(dealStr);
while (matcher.find()) {
String[] ss = new String[array.length];
for (int i = 0; i < array.length; i++) {
ss[i] = matcher.group(array[i]).trim();
}
list.add(ss);
}
return list;
}

/**
* Description:

* @author earn
* @date 2016年5月16日
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}

1 0
原创粉丝点击