forked from tanglijiong/MyJavaStudio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegexUtils.java
More file actions
83 lines (74 loc) · 1.99 KB
/
Copy pathRegexUtils.java
File metadata and controls
83 lines (74 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.xjj.util;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 正则表达式工具
* @author XuJijun
*
*/
public class RegexUtils {
/**
* 使用正则表达式REGEX从文本INPUT(比如html文档)中获取匹配的字符串
* @param INPUT
* @param REGEX
* @return 匹配到的所有字符串
*/
public static List<String> getContentByPattern(String INPUT, String REGEX){
List<String> resultList = new ArrayList<>();
Pattern p = Pattern.compile(REGEX); //根据正则表达式构造一个Pattern对象
if(INPUT==null){
System.out.println("INPUT不能为NULL!");
return resultList;
}
if(p==null){
System.out.println("构造Pattern时发生错误!");
return resultList;
}
Matcher m = p.matcher(INPUT); //利用patter对象为被匹配的文本构造一个Matcher对象
while(m.find()){ //如果在任何位置中发现匹配的字符串……
resultList.add(m.group()); //保存匹配到的字符串
}
return resultList;
}
/**
* 使用正则表达式REGEX从文本INPUT中获取第一个匹配的字符串
* @param INPUT
* @param REGEX
* @return
*/
public static String getFirstMatch(String INPUT, String REGEX){
List<String> ss = getContentByPattern(INPUT, REGEX);
if(ss.size()>0){
return ss.get(0);
}else {
return null;
}
}
/**
* 根据正则表达式REGEX,把INPUT中所有被匹配到的字符串替换成REPLACE
* @param INPUT
* @param REGEX
* @param REPLACE
*/
public static String replaceContentByPattern(String INPUT, String REGEX, String REPLACE){
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
return m.replaceAll(REPLACE);
}
/**
* 从INPUT中找到第一串数字
* @param INPUT
* @return
*/
public static String findFirstNumber(String INPUT){
Pattern p=Pattern.compile("\\d+");
Matcher m=p.matcher(INPUT);
if(m.find()){
return m.group();
}else {
return null;
}
}
}