ps0604
ps0604

Reputation: 1081

Javascript regex - how to match when no trailing spaces

In this regex I'm trying to extract the list of tables from a SQL select statement. It works fine with one exception, if the statement ends with the table name there is no match. For example:

Given he regex:

(?:from|join)\s+(.*?)(?:\)|\s+(?:where|on|inner|outer|full|left|right|join|\s*$))

and given this string:

"select xxxx  from table1 t1, table2, table3 t3 "  (note the last space)

The match is:

"table1 t1, table2, table3 t3"   

But given this string:

"select xxxx  from table1 t1, table2, table3 t3"  (without last space)

There's no match. How to make this work?

Upvotes: 0

Views: 126

Answers (1)

Maraboc
Maraboc

Reputation: 11093

RegEx isn't very good at this, as it's a lot more complicated than it appears:

  • What if they use LEFT/RIGHT INNER/OUTER/CROSS/MERGE/NATURAL joins instead of the a,b syntax? The a,b syntax should be avoided anyway.
  • What about nested queries?
  • What if there is no table (selecting a constant)
  • What about line breaks and other whitespace formatting?
  • Alias names?

What you can do is an sql parser, and there is a good one Hrer.

See more answers in this post.

Upvotes: 1

Related Questions