これには、正規表現とマッチャーを使用できます。ただし、文字列のリストは使用できませんが、実行時に作成できます。
Matcher m = Pattern.compile("^(//|/\\*|\\*|\\{|\\}).*").matcher("");
if (!matcher.reset(strLine).matches()) {
// does not start
}
サンプル :
String str = "abc\n// foo\n/* foo */\nthing\n{bar\n{baz\nlol";
Matcher matcher = Pattern.compile("^(//|/\\*|\\*|\\{|\\}).*").matcher("");
for (String strLine : str.split("\n")) {
if (!matcher.reset(strLine).matches()) {
System.out.println(strLine + " does not match");
}
}
プリント:
abc does not match
thing does not match
lol does not match
以下を使用して、パターンを動的に構築できますPattern.quote
。
public static Pattern patternOf(List<String> starts) {
StringBuilder b = new StringBuilder();
for (String start: starts) {
b.append("|").append(Pattern.quote(start));
}
return Pattern.compile("^(" + b.substring(1) + ").*");
}
// use it like this:
Matcher matcher = patternOf(Arrays.asList("//", "/*", "*", "{", "}")).matcher("");
// produces a pattern like: ^(\Q//\E|\Q/*\E|\Q*\E|\Q{\E|\Q}\E).*