RegExp@Java
對於Regular Expression,可在$JavaDoc/api/java/util/Scanner.html中略知。
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
import java.util.Scanner; String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input); s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"); MatchResult result = s.match(); for (int i=1; i<=result.groupCount(); i++) System.out.println(result.group(i); s.close();Scanner的物件可以用findInLine(RegExp)來比對字串,然後利用match傳回RegExp物件,再利用此RegExp物件的group找出所要的字串,很類似python的作法。 The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace. The findInLine(java.lang.String), findWithinHorizon(java.lang.String, int), and skip(java.util.regex.Pattern) methods operate independently of the delimiter pattern. These methods will attempt to match the specified pattern with no regard to delimiters in the input and thus can be used in special circumstances where delimiters are not relevant. These methods may block waiting for more input.