首先假如有這樣一串字符串:
String s = "共 100 頁, 1 2 3 4...";
假如我想把"100"給取出來,該如何做?
方法一: 采用split的方式
1
|
System.out.println(s.split( " " )[ 1 ]);或者System.out.println(s.split( "\\s" )[ 1 ]); |
假如空" "有多個時,可以這樣:
1
|
System.out.println(s.split( "\\s+" )[ 1 ]); |
注:split是支持正則的,\s在正則中表示空格,+在正則中表示至少1個,即1個或多個,所以\s+表示至少有一個空格
方法二: 采用indexOf的方式
1
2
3
|
int begin = s.indexOf( " " ); int end = s.indexOf( " " , begin+ 1 ); System.out.println(s.substring(begin+ 1 , end)); |
方法三: 正則
封裝好的一個正則類:
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
|
public class RegExp { public boolean match(String reg, String str) { return Pattern.matches(reg, str); } public List<String> find(String reg, String str) { Matcher matcher = Pattern.compile(reg).matcher(str); List<String> list = new ArrayList<String>(); while (matcher.find()) { list.add(matcher.group()); } return list; } public String find(String reg, String str, int index) { Matcher matcher = Pattern.compile(reg).matcher(str); if (matcher.find()) { return matcher.group(index); } return null ; } public String findString(String reg, String str) { String returnStr = null ; List<String> list = this .find(reg, str); if (list.size() != 0 ) returnStr = list.get( 0 ); return returnStr; } } |
1
2
3
4
|
RegExp re = new RegExp(); System.out.println(re.findString( "\\d+" , s)); System.out.println(re.findString( "(?<=共).*?\\d+" , s).trim()); |
注:正則中\(zhòng)d表示數(shù)字,(?<=共)是一種預(yù)查模式
方法四: 采用replaceFirst的方式
1
|
System.out.println(s.replaceFirst( ".*?(\\d+).*" , "$1" )); |
replaceFirst也是支持正則的
注: ?在正則中表示最小匹配模式,$1表示第一個()表示式里面的內(nèi)容。
總結(jié)
以上四種方法中,其中有三種都與正則有關(guān)系,所以,要想玩轉(zhuǎn)字符串的操作,具備一定的正則表示式的能力還是很有必要的!
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
原文鏈接:http://www.cnblogs.com/zhangfei/p/5092220.html