我有两个字符串
left join orderitem on order.id = orderitem.orderid right join product on product.id = orderitem.productid join orders on customers.customerid=orders.customerid;
我想要的第一个字符串:
=> left join orderitem on order.id = orderitem.orderid
=> right join product on product.id = orderitem.productid
=> join orders on customers.customerid=orders.customerid
第二个字符串:
join orderitem on order.id = orderitem.orderid right join product on product.id = orderitem.productid join orders on customers.customerid=orders.customerid group by id;
我想要的第二个字符串:
=> join orderitem on order.id = orderitem.orderid
=> right join product on product.id = orderitem.productid
=> join orders on customers.customerid=orders.customerid
这就是我所做的......但它没有正常工作......
/([inner|left|right|full]*?\s.+?(?:inner|left|right|full|join|;))/
答案 0 :(得分:2)
所以我不确定你是否只想要一个适合你已尝试的解决方案?
我发现以下内容提供了所需的输出:
/(.*?= ?[^ ;]*) ?/
如果您需要使用当前正则表达式选项的解决方案,我可能需要更长的时间来解决它:)
答案 1 :(得分:2)
正如其他答案中所指出的,使用正则表达式可能不是最佳方法。
您可以使用Ruby的SQL解析器,如sql-parser
使用它,解析你的字符串很容易。
在sql-parser的代码中,您可以看到它knows how to parse different types of JOIN statements
答案 2 :(得分:1)
虽然尝试使用正则表达式解析SQL是不可能的,但是对于这个特定示例,您可以尝试:
/(((inner|left|right|full)\s+)?join\s+[^=]*=\s*\S+\b)/
> regexp = /(((inner|left|right|full)\s+)?join\s+[^=]*=\s*\S+\b)/
> str1 = "left join orderitem on order.id = orderitem.orderid right join product on product.id = orderitem.productid join orders on customers.customerid=orders.customerid;"
=> "left join orderitem on order.id = orderitem.orderid right join product on product.id = orderitem.productid join orders on customers.customerid=orders.customerid;"
> str1.scan(regexp).map(&:first)
=> ["left join orderitem on order.id = orderitem.orderid", "right join product on product.id = orderitem.productid", "join orders on customers.customerid=orders.customerid"]