首先假如有這樣一串字符串:
String s = "共 100 頁, 1 2 3 4...";
假如我想把"100"給取出來,該如何做?
方法一: 采用split的方式
System.out.println(s.split(" ")[1]);或者System.out.println(s.split("http://s")[1]);假如空" "有多個時,可以這樣:
System.out.println(s.split("http://s+")[1]);注:split是支持正則的,/s在正則中表示空格,+在正則中表示至少1個,即1個或多個,所以/s+表示至少有一個空格
方法二: 采用indexOf的方式
int begin = s.indexOf(" ");int end = s.indexOf(" ", begin+1);System.out.println(s.substring(begin+1, end));方法三: 正則
封裝好的一個正則類:
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; } } RegExp re = new RegExp(); System.out.println(re.findString("http://d+", s)); System.out.println(re.findString("(?<=共).*?//d+", s).trim());注:正則中/d表示數字,(?<=共)是一種預查模式
方法四: 采用replaceFirst的方式
System.out.println(s.replaceFirst(".*?(//d+).*", "$1"));replaceFirst也是支持正則的
注: ?在正則中表示最小匹配模式,$1表示第一個()表示式里面的內容。
總結
以上四種方法中,其中有三種都與正則有關系,所以,要想玩轉字符串的操作,具備一定的正則表示式的能力還是很有必要的!
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.VeVB.COm/regex/javascript
正則表達式在線生成工具:
http://tools.VeVB.COm/regex/create_reg
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
新聞熱點
疑難解答