compile()に加えて、JavaPatternにはオーバーロードされたメソッドがあります。
public static Pattern compile(String regex, int flags)
フラグは、Patternクラスの定数です。
国旗 | 特徴 |
---|---|
CASE_INSENSITIVE(?i) | これは、通常の照合では大文字と小文字が無視され、US-ASCII文字で実行されることを意味します。UNICODE_CASEマークと組み合わせることができ、Unicodeベースの大文字と小文字を区別しないマッチングをオンにすることができます |
コメント(?x) | 行末までの#で始まる空白とコメントは無視されます |
DOTALL(?s) | このモードでは、新しい行. を含むすべての文字に一致します。デフォルト. では、新しい行以外の任意の文字に一致します。 |
マルチライン(?m) | 文字列全体の最初と最後だけでなく、任意の行の最初と最後と一致するように、変更^ と$ 意味を設定します。注:(?M)のみ複数行に関与正規表現の中^ や$ 試合は複数行モードを使用することになります。 |
UNIX_LINES(?d) | では. 、^ 、& 改行を認識だけで行動します\n |
他にもフラグがあります。パターンの定数と説明を参照できます。
栗をいくつか見てみましょう。
マルチラインモード(?m)
複数行モードでは、各行(この行の最初の文字から各行の終わりまで)が一致します。
public class MultiLinesFlags {
static public final String POEM =
"Twas brillig, and the slithy toves\n" +
"Did gyre and gimble in the wabe.\n" +
"All mimsy were the borogoves,\n" +
"And the mome raths outgrabe.\n\n" +
"Beware the Jabberwock, my son,\n" +
"The jaws that bite, the claws that catch.\n" +
"Beware the Jubjub bird, and shun\n" +
"The frumious Bandersnatch.";
public static void main(String[] args) {
// 这个正则表达式中有一个「$」行尾的匹配
// \S: 匹配任意不是空白符的字符
// \s: 匹配任意的空白符
Matcher m =
Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$")
.matcher(POEM);
while (m.find()) {
for (int j = 0; j <= m.groupCount(); j++)
print("[" + m.group(j) + "]");
print();
}
}
}
大文字と小文字を区別しない(?i)
public class CaseSensitive {
public static void main(String[] args) {
// (?i) 忽略大小写
String reg = "(?i)((^[aeiou])|(\\s+[aeiou]))\\w+?[aeiou]\\b";
print("Regular expression: \"" + reg + "\"");
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher("Arline ate eight apples and one orange while Anita hadn't any");
while (m.find()) {
print("Match \"" + m.group() + "\" at position " +
m.start() + ((m.end() - m.start() < 2) ? "" : ("-" + (m.end() - 1))));
}
}
}
複数のフラグを組み合わせる
public class ConjunctionFlags {
public static void main(String[] args) {
Pattern p = Pattern.compile("^java",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Matcher m = p.matcher(
"java has regex\nJava has regex\n" +
"JAVA has pretty good regular expressions\n" +
"Regular expressions are in Java");
while (m.find())
System.out.println(m.group());
}
}
PS:上記の栗はすべて「JavaProgrammingThoughts」からのものです