我有一个mysql表名xyz,它有两列tc_name和tc_path,其中tc_path类似于/ a / b / c / x / tc_name,tc_name为null。我想在列(tc_name)中插入值tc_path列值。 我知道它会像我们在其他语言中使用正则表达式那样。但我不知道如何在Mysql中执行此操作。 我找到了这个函数:
// get all the rows
let bookings = getRowsFromSpreadsheet;
// start with row 0 and make a booking. Pass in the ENTIRE LIST,
// a pointer that starts at 0, and a final callback function that
// will be called when the list is done.
makeABooking(bookings, 0, function () {
console.log('done');
});
// this is a recursive function
function makeABooking(bookings, pointer, callback) {
// Grab data from the rows spreadsheet rows to send to
// Bookio. This example just has two fields.
let name = bookings[pointer].name;
let number = bookings[pointer].number;
// some function that sends stuff to Bookio
sendToBookio(name, number, function(response) {
// when you get the response back, increase the pointer
pointer++;
// check to see if there are more rows from the spreadsheet
if(pointer < bookings.length) {
// if there are, make another booking, pass in
// the entire list again, the pointer that was
// incremented and the final callback that gets
// called when everything is done
makeABooking(bookings, pointer, callback);
} else {
// looks like they're all done, call that final
// callback
callback();
}
});
}
我试过了:
DELIMITER $$
CREATE FUNCTION `regex_replace`(pattern VARCHAR(1000),replacement VARCHAR(1000),original VARCHAR(1000))
RETURNS VARCHAR(1000)
DETERMINISTIC
BEGIN
DECLARE temp VARCHAR(1000);
DECLARE ch VARCHAR(1);
DECLARE i INT;
SET i = 1;
SET temp = '';
IF original REGEXP pattern THEN
loop_label: LOOP
IF i>CHAR_LENGTH(original) THEN
LEAVE loop_label;
END IF;
SET ch = SUBSTRING(original,i,1);
IF NOT ch REGEXP pattern THEN
SET temp = CONCAT(temp,ch);
ELSE
SET temp = CONCAT(temp,replacement);
END IF;
SET i=i+1;
END LOOP;
ELSE
SET temp = original;
END IF;
RETURN temp;
END$$
如果tc_path = / a / b / c / d,它应该给我tc_name = d 但相反,它给了我abcd。 我使用了错误的功能,或者我不知道如何使用它。 请建议一些查询。
请帮助!!!
由于
答案 0 :(得分:0)
上面的函数将替换与正则表达式匹配的单个字符,但它不是完整的正则表达式替换。基本上,错误的功能。
Mysql现在不是很好 - 你可能想要考虑另一条路径,就像雅克建议的那样,用简单的字符串替换。
如果你真的想要一个正则表达式解决方案,也许可以查看一个更完整的mysql正则表达式库: https://github.com/mysqludf/lib_mysqludf_preg
答案 1 :(得分:0)
在 THIS 特殊情况下,您尝试获取路径的最后一部分,可以跳过正则表达式并使用简单的字符串函数:
update testplans set tc_name=substr(tc_path, length(tc_path)-locate('/',reverse(tc_path))+2);
按相反顺序进行搜索
正确的正则表达式是
.*/([^/]*)
但你需要提取最后一部分,而MySQL实际上并没有这样做。 MariaDB 10有一个可能有帮助的REGEXP_REPLACE。