Fabio Delarias
Fabio Delarias

Reputation: 380

What is the Regex For the following pattern

requrements:

1)So basically I need that the words in backticks have to be [A-Za-z0-9]+

2) the number of words in back ticks is unknown but MUST be in sequence and seperated by a comma

3) after 'FROM' the string must be [A-Za-z0-9]+

this is what I have so far:

   String command = "SHOW TABLE COLUMNS `abcdf123`,`abcdf123`,`abcdf123` FROM ABCDF123";
   Match CMD = Regex.Match(command, @"SHOW(\s+)TABLE(\s+)COLUMNS(\s+)(a sequence of words enclosed in backticks seperated by a coma)(\s+)FROM(\s+)([A-Za-z0-9]+)", RegexOptions.IgnoreCase);
        if (CMD.Success)
            return true;
       else
        return false;

any Ideas would be greatly apreciated I am still new to Regex

Upvotes: 0

Views: 355

Answers (3)

Santhosh Gutta
Santhosh Gutta

Reputation: 346

The regex for matching your command string is:

^[^`]*?`([^`]+)`+[\s\S]*?FROM\s+([a-zA-Z\d]+)[\s\S]*$


`([^`]+)` - will match data between backticks and the matching continues until
FROM is encountered.

([a-zA-Z\d]+)  - will match text after FROM clause (expecting that there is 
atlest one space after FROM)

The text matched in backticks can be obtained by using \1 (group 1 matching) and the text after FROM clause can be obtained by using \2 (group 2 matching).

Upvotes: 0

Gusdor
Gusdor

Reputation: 14322

This will do it:

\ASHOW TABLE COLUMNS (?:`(?<column_name>[a-zA-Z0-9]+)`,?)+ FROM (?<table_name>[a-zA-Z0-9]+)\z

Regular expression visualization

Debuggex Demo

Fails if a non alphanumeric character exists between backtick pairs.

Test 1

All alphanumeric. Expected to pass.

SHOW TABLE COLUMNS `abcdf123`,`abcdf123`,`abcdf123` FROM ABCDF123

MATCHED

Test 2

Single non-alphanumeric character between one backtick pair. Expected to fail.

SHOW TABLE COLUMNS `abcdf123`,`abcdf123*`,`abcdf123` FROM ABCDF123

NO MATCH

Test 3

Single non-alphanumeric character in table name. Expected to fail.

SHOW TABLE COLUMNS `abcdf123`,`abcdf123`,`abcdf123` FROM ABCDF123*

NO MATCH

Upvotes: 1

gpmurthy
gpmurthy

Reputation: 2427

Consider the following Regex...

SHOW(\s+)TABLE(\s+)COLUMNS(\s+)(\`[\w\d]*?\`\,?)+FROM(\s+)([A-Za-z0-9]+)

Good Luck!

Upvotes: 0

Related Questions