從jse1.4
String
- 兩個split
方法是新的。 subSequence方法已被添加,正如String現在實現的CharSequence接口所要求的那樣。已添加三種其他方法:matches
,replaceAll
和replaceFirst
。
使用Java String.split(String regex, int limit)
與Pattern.quote(String s)
字符串 「BOO:和:foo」 的,例如,產生具有這些參數的如下結果:
Regex Limit Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
String str = "abc?def,ghi?jkl,mno,pqr?stu,vwx?yz";
String quotedText = Pattern.quote("?");
// ? - \\? we have to escape sequence of some characters, to avoid use Pattern.quote("?");
String[] split = str.split(quotedText, 2); // ["abc", "def,ghi?jkl,mno,pqr?stu,vwx?yz"]
for (String string : split) {
System.out.println(string);
}
我有臉在URL參數中的同樣的問題,爲了resoleve它,我需要根據第一個?
拆分因此,剩餘字符串包含參數值,他們需要根據&
拆分。
String paramUrl = "https://www.google.co.in/search?q=encode+url&oq=encode+url";
String subURL = URLEncoder.encode(paramUrl, "UTF-8");
String myMainUrl = "http://example.com/index.html?url=" + subURL +"&name=chrome&version=56";
System.out.println("Main URL : "+ myMainUrl);
String decodeMainURL = URLDecoder.decode(myMainUrl, "UTF-8");
System.out.println("Main URL : "+ decodeMainURL);
String[] split = decodeMainURL.split(Pattern.quote("?"), 2);
String[] Parameters = split[1].split("&");
for (String param : Parameters) {
System.out.println(param);
}
Run Javascript on the JVM with Rhino/Nashorn«使用JavaScript的String.prototype.split
功能:
var str = "abc?def,ghi?jkl,mno,pqr?stu,vwx?yz";
var parts = str.split(',');
console.log(parts); // (5) ["abc?def", "ghi?jkl", "mno", "pqr?stu", "vwx?yz"]
console.log(str.split('?')); // (5) ["abc", "def,ghi", "jkl,mno,pqr", "stu,vwx", "yz"]
var twoparts = str.split(/,(.+)/);
console.log(parts); // (3) ["abc?def", "ghi?jkl,mno,pqr?stu,vwx?yz", ""]
console.log(str.split(/\?(.+)/)); // (3) ["abc", "def,ghi?jkl,mno,pqr?stu,vwx?yz", ""]
我試過這段代碼,併爲我工作@Razib正確的s到strr。 –