Từ jse1.4
String
-Hai split
phương pháp mới. Phương thức subSequence đã được thêm vào, theo yêu cầu của giao diện CharSequence mà String hiện đang thực hiện. Ba phương thức bổ sung đã được thêm vào: matches
, replaceAll
và replaceFirst
.
Sử dụng Java String.split(String regex, int limit)
với Pattern.quote(String s)
Chuỗi "boo: và: foo", ví dụ, mang lại kết quả như sau với các thông số:
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);
}
Tôi có khuôn mặt cùng một vấn đề trong các tham số URL, Để resoleve nó tôi cần phải phân chia dựa trên ?
đầu tiên Vì vậy, String remaing chứa các giá trị tham số và chúng cần phải được chia dựa trên &
.
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 «Với String.prototype.split
hàm JavaScript của:
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", ""]
Tôi đã thử mã này và làm việc cho tôi @Razib đúng s để strr. –