import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^from\\s+\n"
+ "(?P<package_name>[.\\w]+)\\s+\n"
+ "import\\s+\n"
+ "(\\()?\n"
+ "(?(2)\n"
+ " (?P<object>[^()]+)\\)\n"
+ " |\n"
+ " (?P<object2>(?:.+[\\n\\r]?)+)\n"
+ ")";
final String string = "from .sql.base import (\n"
+ " SchemaVisitor\n"
+ " )\n"
+ "import os # ignore this import\n"
+ "from _pytest.config import (\n"
+ " main, UsageError, cmdline,\n"
+ " hookspec, hookimpl\n"
+ ")\n\n"
+ "I can capture this with:\n\n"
+ "syntax1 = re.compile(r'^ *from (?P<package>[.\\w]+) +import +\\(?(?P<objects>[*, \\n\\w]+)\\)? *$',\n"
+ " flags=re.MULTILINE)\n\n"
+ "Syntax #2 uses line continutation (if needed), and technically has no newlines within the import statement:\n\n"
+ "from pandas import Series\n\n"
+ "from .solvers import solve, solve_linear_system, solve_linear_system_LU, \\\n"
+ " solve_undetermined_coeffs, nsolve, solve_linear, checksol, \\\n"
+ " det_quick, inv_quick, check_assumptions\n\n"
+ "from .ode import checkodesol, classify_ode, dsolve, \\\n"
+ " homogeneous_order";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.COMMENTS);
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