In the previous section we learned the first method - parsing strings using default delimiters. In this section we learn the second method - parsing strings using regular expressions as delimiters .
We need to know that if the Scanner object wants to use the default separation mark, which is a space, to parse the data in the string, it is required to use spaces to separate the data in the string from other characters, otherwise it will not be able to parse what we need. data.
In fact, the Scanner object can also call methods:
useDelimiter(regular expression);
Use regular expressions as delimiters, that is to say, when the Scanner object parses strings, it uses strings that match the regular expression as delimiters.
For example, parse the string using the regular expression (matches all non-numeric strings) String regex = [^0123456789.]+ as the delimiter mark.
importjava.util.*;publicclassMain{publicstaticvoidmain(Stringargs[]){Stringcost=Telephone bill list: local call fee 66.66 yuan, long-distance call fee 166.66 yuan, text message fee 16.16 yuan;Scannerscanner=newScanner(cost);scanner.useDelimiter([^0123456789. ]+);//scanner sets the separation mark doublesum=0;while(scanner.hasNext()){try{doubleprice=scanner.nextDouble();sum=sum+price;System.out.println(price);}catch (InputMismatchExceptionexp){Stringt=scanner.next();}}System.out.println(Total communication cost: +sum+yuan);}}
The running results are as follows:
66.66166.6616.16 Total communication cost: 249.48 yuan