import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?:\\[[^\\]\\[\\n]*\\]\\s+)?(?<name>[^)(\\n]*)\\s*(\\((?!not|unus)[^)(\\n]*\\))?";
final String string = "[Example] öäüß asdf 1234 (1aö)\n"
+ "[Red] Panda (It's so cute)\n"
+ "[Red] The Panda (It's so cute),\n"
+ "[Red] what Panda (It's so cute) (not necessary),\n"
+ "[Red] it's a Panda (It's so cute) (unusual),\n"
+ "[Yellow] Leopard (the big one)\n"
+ "[Yellow] The Leopard (the big one),\n"
+ "[Yellow] what Leopard (the big one) (not needed),\n"
+ "[Yellow] it's a Leopard (the big one) (unusual),\n"
+ "[Green] Dragon (Fire? It's hot!)\n"
+ "[Green] The Dragon (Fire? It's hot!),\n"
+ "[Green] what Dragon (Fire? It's hot!) (not usual),\n"
+ "[Green] it's a Dragon (Fire? It's hot!) (unusual),\n"
+ "[Blue] Snake (zzzZZZzzzZZZ)\n"
+ "[Blue] The Snake (zzzZZZzzzZZZ),\n"
+ "[Blue] what Snake (zzzZZZzzzZZZ) (not beautiful),\n"
+ "[Blue] it's a Snake (zzzZZZzzzZZZ) (unusual),\n"
+ "Panda (It's so cute)\n"
+ "The Panda (It's so cute),\n"
+ "what Panda (It's so cute) (not necessary),\n"
+ "it's a Panda (It's so cute) (unusual),\n"
+ "Leopard (the big one)\n"
+ "The Leopard (the big one),\n"
+ "what Leopard (the big one) (not usual),\n"
+ "it's a Leopard (the big one) (unusual),\n"
+ "Dragon (Fire? It's hot!)\n"
+ "The Dragon (Fire? It's hot!),\n"
+ "what Dragon (Fire? It's hot!) (not necessary),\n"
+ "it's a Dragon (Fire? It's hot!) (unusual),\n"
+ "Snake (zzzZZZzzzZZZ)\n"
+ "The Snake (zzzZZZzzzZZZ),\n"
+ "what Snake (zzzZZZzzzZZZ) (not beautiful),\n"
+ "it's a Snake (zzzZZZzzzZZZ) (unusual),\n"
+ "Panda\n"
+ "The Panda,\n"
+ "what Panda (not necessary),\n"
+ "it's a Panda (unusual),\n"
+ "Leopard\n"
+ "The Leopard,\n"
+ "what Leopard (not needed),\n"
+ "it's a Leopard (unusual),\n"
+ "Dragon\n"
+ "The Dragon,\n"
+ "what Dragon (not usual),\n"
+ "it's a Dragon (unusual),\n"
+ "Snake \n"
+ "The Snake ,\n"
+ "what Snake (not beautiful),\n"
+ "it's a Snake (unusual),";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html