Today the testers made a small demand, IP address a.b.c.d, abcd any one domain is empty when treated as 0. For example 192 ... , the backstage as 192.0.0.0 processing.
The way I think of it is to use the split method of the string, first get the value of ABCD four fields, assuming that Text1 is the actual text value obtained by the IP address control, TEXT2 is the converted value.
String Text1 = "192 ...";
string[] Fields = text1.split ("\ \");
System.out.println (arrays.tostring (fields)); [192]
Regular expression for matching if the trailing string is matched to n strings consecutively, the n strings are ignored.
The regular expression used for matching in this example is "\ \", that is, to escape the dot number to a normal symbol. Point number Again "192 ..." The tail continuously matches three points. So these three dot numbers are ignored, which is actually equivalent to
Text1= "192" for another example:
String Text1 = "88814534212"; string[] = Text1.split ("[12345]"); System.out.println (arrays.tostring (Fields));
Guess what the result is?
Not to solve my actual problem, in the actual application scenario, the user must be able to enter "192 ...", "..." and other IP, I need to convert to "192.0.0.0" and "0.0.0.0",
The plan I'm thinking of is:
String Text1 = "..."= (text1+ ""). Split ("\ \");
System.out.println (arrays.tostring (Fields)); [,, 3,]
After adding a space to the end of the string, the dot number cannot be matched to a string at the end of the string, so there is no ignored string, so the array in the previous split is then placed "", "" "," ", and I just need to replace the empty string or space with 0 to achieve the result I want.
String text1 = "..."; // split string text1
String [] fields = (text1 + "") .split ("\\."); // Split text1 into array fields
System.out.println (Arrays.toString (fields));
for (int i = 0; i <fields.length; i ++) {
if (fields [i] .trim (). equals ("")) {
fields [i] = "0";
}
}
String text2 = "";
for (String string: fields) {
text2 + = string + ".";
}
text2 = text2.substring (0, text2.lastIndexOf ("."));
System.out.println (text2);
A small problem with Java split