Reputation: 8758
I'm trying to parse a simple DDL statement. First I'm trying to pull the table name out. The syntax will be something like 'CREATE TABLE DB_NAME.TABLE_NAME'
So far I've got this:
String line = "CREATE TABLE DB_NAME.T_NAME";
String pattern = ".*?\\bTABLE\\s+(\\w+)\\b.*";
System.out.println(line.replaceFirst(pattern, "$1"));
That gives me back "DB_NAME". How can I get it to give me back "T_NAME"?
I tried following the update in this answer, but I couldn't get it to work, probably due to my very limited regex skills.
Upvotes: 0
Views: 1004
Reputation: 17048
Here's a small piece of code that will do (using named capturing groups):
String line = "CREATE TABLE DB_NAME.T_NAME";
Pattern pattern = Pattern.compile("CREATE TABLE (?<database>\\w+)\\.(?<table>\\w+)");
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
String database = matcher.group("database"); // DB_NAME
String table = matcher.group("table"); // T_NAME
}
Upvotes: 2
Reputation: 627468
You may extract all the string after the TABLE
into a group and then split with comma to get individual values:
String line = "CREATE TABLE DB_NAME.T_NAME";
String pattern = "\\bTABLE\\s+(\\w+(?:\\.\\w+)*)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(line);
if (m.find()){
System.out.println(Arrays.toString(m.group(1).split("\\.")));
// => [DB_NAME, T_NAME]
}
See the Java demo.
If you are sure of the incoming format of the string, you might even use
"\\bTABLE\\s+(\\S+)"
See another Java demo.
While \w+(?:\.\w+)*
matches 1+ word chars followed with 0+ repetitions of .
and 1+ word chars, \S+
plainly matches 1+ non-whitespace chars.
Upvotes: 1