I'm trying to get list of phrases on string with regex, i need to get this:
- "teste"
on:
CREATE TABLE teste
or
CREATE TABLE IF NOT EXISTS teste
I'm trying this:
CREATE (TABLE|TABLE IF NOT EXISTS) ([a-zA-Z]+)
Any sugestions ?
Thanks !
-- update
I need get only "teste"... how I can get in this expression that if I need use parenthesis on "table group" ?
Balancin, do you want find this in java?
String regexToFind = ".*[tT][eE][sS][tT][eE].*";
String inputOk = "CREATE TABLE teste ";
String inputNotOk = "CREATE TABLE notok ";
System.out.println(inputOk.matches(regexToFind));
System.out.println(inputNotOk.matches(regexToFind));
Your expression is not working as expected because the order of the operands for the alternation operator (|) matter to some engines. What happens is: as soon as it matches TABLE, the engine will not continue and try to match the second operand (TABLE IF NOT...) because it will consider the group matched and go on, thus the IF NOT... part would be matched by the ([a-zA-Z]+) expression.
The cleanest/safest solution would be to use the ? operator to make the expression optional:
CREATE TABLE( IF NOT EXISTS)? ([a-zA-Z]+)
Demo here.
Or change the order of the operands in the alternation operator | (it matters to some engines):
CREATE (TABLE IF NOT EXISTS|TABLE) ([a-zA-Z]+)
Demo for this second one.
Also note that the word "teste" on your example would be matched by the group number two. If you want it to be matched by the first group, use non-capturing groups (through ?:) as in:
CREATE TABLE(?: IF NOT EXISTS)? ([a-zA-Z]+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With