给定这两个字符串:
let query = "select color, year from car where color = blue and year = 2002";
Run Code Online (Sandbox Code Playgroud)
或者
let query = "select color, year from car";
Run Code Online (Sandbox Code Playgroud)
我创建了以下内容RegExp来String.prototype.match提取列、表名和 where 子句(可选)
var results = query.match(/select (.*) from (.*) where (.*)/);
Run Code Online (Sandbox Code Playgroud)
对于第一个查询,结果是我所期望的:
[
'select color, year from car where color = blue and year = 2002',
'color, year',
'car',
'color = blue and year = 2002',
index: 0,
input: 'select color, year from car where color = blue and year = 2002'
]
Run Code Online (Sandbox Code Playgroud)
对于第二个查询,我得到一个 null,如果我尝试更改 RegExp 以考虑 where 子句可选,它会更改捕获组并且也不起作用:
var results = query.match(/select (.*) from (.*)( where (.*))?/);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您知道如何使用捕获组(其中一个是可选的)吗?我有其他策略来实现这一点,但我真的很想继续使用捕获组。
谢谢
答案是用非捕获组包围可选的 WHERE 子句并使其成为可选的。我还稍微更改了它,因为您可能不想匹配任何字符.。您随时可以将其改回来。
var regex = /select\s+([\w ,]+)\s+from\s+(\w+)(?:\s+where([\w =]+))?/gi;
Run Code Online (Sandbox Code Playgroud)
如果我没有提到使用正则表达式处理代码是一个糟糕的主意,那我就失职了。您始终可以使用 SQL 解析器。