我就廢話不多說了,大家還是直接看代碼吧~
1
2
3
4
5
6
7
8
9
10
11
12
|
String str = "哈哈<font color='red'>1111</font>還是你牛<font color='red'>11111</font> " ; String regStr = "<font color='red'>(.*?)</font>" ; Pattern pattern = Pattern.compile(regStr); if (str != null ){ Matcher m = pattern.matcher(str); while (m.find()){ String group = m.group( 1 ); System.out.println(group); str = str.replaceAll(regStr, "***" ); } System.out.println(str); } |
結果:
1
2
3
|
1111 11111 哈哈***還是你牛*** |
使用Java正則獲取指定字符前或者后數據:
代碼如下:
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
|
<pre name= "code" class = "java" > public class RegTest { //字符串截取 public static String regComp(String item) { String num = "" ; // 替換中文 String reg = "[\\u4e00-\\u9fa5]+" ; //截取λ|入后面數字 String comp1 = "[\\s\\S]*([λ|入]\\d*)[\\s\\S]*" ; //截取波|第前面數字 String comp2 = "(\\d+[波|第])" ; if (item.matches(comp1)) { num = item.replaceFirst(comp1, "$1" ).replaceAll(reg, "" ).replace( "λ" , "" ); } else { Pattern p = Pattern.compile(comp2); Matcher m = p.matcher(item); if (m.find()) { num = m.group( 1 ).replaceAll(reg, "" ); } } return num; } /** * @Description: TODO(這里用一句話描述這個類的作用) * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String str1 = "石家莊(至鄭州)架1-2-23-OTU3S-1(OTU3S 1波).OCH)" ; String str3 = " 北京東四1-1-4D-OTU3S-1(OTU3S 100第三個).OCH" ; String str2 = " 北京東四1-1-4D-OTU3S-1(OTU3S 入12).OCH" ; String str4 = " 北京東四1-1-4D-OTU3S-1(OTU3S λ12334).OCH" ; String[] array = { str1, str2, str3,str4 }; for ( int i = 0 ; i < array.length; i++) { //測試 String num = regComp(array[i]); System.out.println(num); } } } |
輸出結果:
1
2
3
4
|
1 12 100 12334 |
以上這篇Java利用正則取標簽之間的數據就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/lipr86/article/details/90906311