Special symbols in Java split() method

1. What is split?

In Java, the split() method is used to separate strings, and the string can be split based on matching a given regular expression. The split() method can split a string into substrings, and then return the result as a string array; the syntax is as follows, where the parameter regex specifies the regular expression separator, and limit specifies the number of splits. The delimiter can be any character, symbol, number, string, etc.

stringInfo.split([regex,[limit]])

2. Special character processing

1. Case

private String data = "6&three-1 cabinet^7&three-2 cabinet^8&customer service center";
The string is converted into a List array, including id and name in the array

This involves special character splitting. If data.split("^"); is split according to the tradition, the output result is still the string itself, so when it comes to special character splitting, an escape character should be added in front of it.

String data = "6&三-1号柜^7&三-2号柜^8&客服中心";
List<Pair<String, String>> list = new ArrayList<>();
String[] elements = data.split("\\^");
for (String element : elements) {
    String[] parts = element.split("&");
    String id = parts[0];
    String name = parts[1];
    list.add(new Pair<>(id, name));
}

There is also a multi-symbol segmentation. In this case, it is not necessary to add escape characters, but also to use separators.

String address="Beijing ^ Beijing @ Haidian District #Sidao Street";
String address = "北京^北京市@海淀区#四道街";
String[]splitAddress=address.split("\\^|@|#");
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);

Summarize

split is a regular expression. Special symbols include   | + * ^ $ / | [ ] ( ) - . \,  etc., because they are part of the regular expression, so if you want to use the character itself, you must use the escape character \\ to escape to express itself

Guess you like

Origin blog.csdn.net/X_sunmmer/article/details/130879198
Recommended