0

I am writing a regex to validate that a name should be given when defining INDEX, KEY and UNIQUE while creating a new table. Some of the valid syntaxes are

KEY `id` (`id`),     
INDEX name (`name`),    
UNIQUE idx (`id`),     
UNIQUE KEY name (`name`),

Invalid syntaxes are

UNIQUE KEY (`name`),   
INDEX (`designation`),     
UNIQUE (`status`),    

because there is no name provided while defining them.

I came up with a regex like this

(?i)(?:UNIQUE\s+KEY|UNIQUE\s+INDEX|KEY|INDEX|UNIQUE)\s*`?\w+`?\s*\(

But it matches

UNIQUE KEY (`name`),

also. Is there anyway I can improve the regex not to match the above string?

6
  • Try (?:KEY\s+`[^`]*`|(?:INDEX|UNIQUE\s+KEY)\s+\w+|UNIQUE\s+(?!KEY\s*\()\w+)\s*\(`[^`]*`\) Commented Jun 10, 2016 at 20:34
  • Sorry for the late reply. When I tried ur regex, I got error for unbalanced paranthesis. Commented Jun 13, 2016 at 18:28
  • Did you copy it from here? It must be a copy/paste issue. It works at the regex101.com. Using ` is tricky inside comments. Commented Jun 13, 2016 at 18:33
  • Thanks anyway @WiktorStribiżew Commented Jun 13, 2016 at 18:40
  • Your "invalid" syntaxes are quite valid. I almost never explicitly name indexes. Commented Jun 20, 2016 at 6:31

1 Answer 1

1

You could add a negative lookahead after the first UNIQUE so that it would try the second OR and only then matches UNIQUE KEY.

(?i)(?:INDEX|UNIQUE(?! KEY)|UNIQUE KEY|KEY)\s+\W?[\w ]+\W?\s+\(\W?[\w ]+\W?\)

And the reverse, if you want to find the nameless which you pointed out as invalid:

(?i)(?:INDEX|UNIQUE(?! KEY)|UNIQUE KEY|KEY)\s+\(\W?[\w ]+\W?\)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.