Andrew
Andrew

Reputation: 8758

Regex - get second word after first match

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

Answers (3)

steffen
steffen

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

Wiktor Stribiżew
Wiktor Stribiżew

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

mrzasa
mrzasa

Reputation: 23347

What about sth like this:

.*?\\bTABLE\\s+\\w+\\.(\\w+)\\b.*

Demo

It first matches the TABLE keyword with .*?\\bTABLE\\s+. Then it matches DB_NAME. with \\w+\\.. Finally it matches and captures T_NAME with (\\w+)

Upvotes: 3

Related Questions