[英]Notepad++ Regular Expression problems
I'm attempting to take some of the work out of pasting in insert statements and formatting them for mysqli prepared statements. 我试图从粘贴插入语句中删除一些工作,并为mysqli准备的语句格式化它们。
Here's an example: 这是一个例子:
INSERT INTO
products
(hash, name, description, large_img, small_img, label_img, category, small, large, small_price, large_price, best_seller, in_stock)
VALUES
([value-1],[value-2],[value-3],[value-4],[value-5],[value-6],[value-7],[value-8],[value-9],[value-10],[value-11],[value-12],[value-13])
So i tried a regex: 所以我尝试了一个正则表达式:
find: (\[.*)(])
replace: ?
but instead of replacing each [value=*]
, it replaces all of them only stopping at the last instance of a closing bracket. 但不是替换每个
[value=*]
,而是替换所有它们,只在最后一个括号中停止。 why? 为什么?
output: 输出:
INSERT INTO
products
(id, hash, name, description, large_img, small_img, label_img, category, small, large, small_price, large_price, best_seller, in_stock)
VALUES
(?)
How can i get it to replace it right. 我如何才能将其更换正确。 Shouldn't my regex select everything until the first closing bracket, but why does it select everything until the last closing bracket?
我的正则表达式不应该选择直到第一个右括号的所有内容,但是为什么它选择直到最后一个右括号的所有内容?
*
is a greedy operator meaning it will match as much as it can and still allow the remainder of the regular expression to match. *
是一个贪婪的运算符,表示它将尽可能匹配,并且仍然允许正则表达式的其余部分匹配。 Use *?
使用
*?
for a non-greedy match meaning "zero or more — preferably as few as possible". 对于非贪婪匹配,意味着“零或更多-最好尽可能少”。
(\[.*?)(])
Note : There is really no need to use capturing groups since you're not referencing them in your replacement call. 注意 :实际上,无需使用捕获组,因为您不在替换呼叫中引用它们。
Find: \[.*?\]
Replace: ?
不要忘记*
是贪婪的,它会尝试尽可能匹配,请使用非贪婪版本:
(\[.*?)(])
As others have said, *
is greedy, while *?
正如其他人所说,
*
是贪婪的,而*?
is non-greedy and will only pick up the minimum amount to match (which is what you're trying to do.) 是非贪婪的,并且只会获取要匹配的最低金额(这就是您要尝试执行的操作。)
However, instead of putting together a string of question marks and commas for PHP why not be lazy and let PHP generate them itself: implode(',', array_fill(0, 13, '?'))
. 但是,与其为PHP放置一串问号和逗号,不如让它变得懒惰并让PHP自己生成它们:
implode(',', array_fill(0, 13, '?'))
。
Feed however many you need in place of that 13
and you've got a reliable set of placeholders less subject to cross-eyed typos. 不管您需要多少喂食来代替那
13
而且您还有一组可靠的占位符,而较少受制于错视错别字。
Example: 例:
$placeholders = implode(',', array_fill(0, 13, '?'));
$sql = <<<SQL
INSERT INTO
products
(id, hash, name, description, large_img, small_img, label_img, category, small, large, small_price, large_price, best_seller, in_stock)
VALUES
($placeholders)
SQL;
echo $sql
: echo $sql
:
INSERT INTO
products
(id, hash, name, description, large_img, small_img, label_img, category, small, large, small_price, large_price, best_seller, in_stock)
VALUES
(?,?,?,?,?,?,?,?,?,?,?,?,?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.