英文:
Go: Format string according to keywords
问题
在Go(golang)中,将字符串格式化为以下形式的最佳方法是什么:
select col1, col2, col3 from foo where col1 > 1000 and col2 < 2000
转换为:
SELECT col1, col2, col3
FROM foo
WHERE col1 > 1000
AND col2 < 2000
最好的方法是将字符串拆分,如果是关键字,在其前面插入"\n"。如果包含AND等内容,则在其前面添加制表符或空格。
但是,如果字符串是这样的:
if (1 > 0)
begin
if (2 > 1)
begin
select * from foo
end
end
那么格式化就会变得更加复杂,因为在begin之后,内部查询需要额外的制表符。而且第二个begin也需要进行格式化。
英文:
In Go (golang) what would be the best way to format a string like this:
select col1, col2, col3 from foo where col1 > 1000 and col2 < 2000
To this:
SELECT col1, col2, col3
FROM foo
WHERE col1 > 1000
AND col2 < 2000
Would it be best to split it up, then if it's a keyword insert a "\n" in front of it. And if it contains AND etc. also add a tab or spaces in front of it.
But what if the string was like this:
if (1 > 0)
begin
if (2 > 1)
begin
select * from foo
end
end
Then the formatting get's a little more complicated, since you would need additional tabs for the inner query after the begin. And also the 2nd begin would also need to be formatted.
答案1
得分: 1
如果你想做得真正正确,你需要一个完整的SQL解析器。这个可能可以工作,但从我看到的输出来看,它并不是你所期望的。所以你需要自己进行调整。
英文:
If you want to do this truly right you need a full-fledged SQL parser. This one could work, but for what I see the output is not really what you are looking for. So you'd need to tweak it yourself.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论