mysql 正则表达式替换内容 红太狼 2022-08-18 13:20 269阅读 0赞 遇到的问题: 以下是[数据库][Link 1]中的一个表mt2: <table style="color:rgb(68,68,68); font-family:Simsun; font-size:15px; line-height:26px; background:rgb(255,187,119)"> <tbody> <tr> <td style="color:rgb(0,0,0); list-style:none; margin:0px; padding:0px"> 代码如下</td> <td align="center" style="color:rgb(0,0,0); list-style:none; margin:0px; padding:0px"> 复制代码</td> </tr> <tr> <td colspan="2" style="color:rgb(0,0,0); list-style:none; margin:0px; padding:10px"> +----+------------------------------------------+ <br> | id | name | <br> +----+------------------------------------------+ <br> | 1 | sdfsf<contact>beijing</contact>sldjfsld | <br> | 2 | sdfsf<contact>shanghai</contact>sldjfsld | <br> | 3 | sdfsf<contact>jn</contact>sldjfsld | <br> | 4 | sdfsf<contact>qd</contact>sldjfsld | <br> +----+------------------------------------------+ </td> </tr> </tbody> </table> 遇到的要求是:将该表中<contact>到</contact>的内容删除。 众所周知,replace函数是不支持正则表达式的,所以只能采用其他的方法处理。 于是,我是使用了下面的sql语句: <table style="color:rgb(68,68,68); font-family:Simsun; font-size:15px; line-height:26px; background:rgb(255,187,119)"> <tbody> <tr> <td style="color:rgb(0,0,0); list-style:none; margin:0px; padding:0px"> 代码如下</td> <td align="center" style="color:rgb(0,0,0); list-style:none; margin:0px; padding:0px"> 复制代码</td> </tr> <tr> <td colspan="2" style="color:rgb(0,0,0); list-style:none; margin:0px; padding:10px"> <p style="list-style:none; margin-top:0px; margin-bottom:0px; padding-top:8px; padding-bottom:8px; font-size:14px; word-wrap:break-word"> update mt2 set name = replace(name, <a href="http://www.111cn.net/tags.php/substr/" style="font-size:15px; color:rgb(45,100,179)" rel="nofollow">substr</a>ing(name, locate('<contact>', name),locate('</contact>', name)-locate('<contact>'+10, name)),''); </p> </td> </tr> </tbody> </table> 字符串(正则) 模糊 问题解决了。 结果: <table style="color:rgb(68,68,68); font-family:Simsun; font-size:15px; line-height:26px; background:rgb(255,187,119)"> <tbody> <tr> <td style="color:rgb(0,0,0); list-style:none; margin:0px; padding:0px"> 代码如下</td> <td align="center" style="color:rgb(0,0,0); list-style:none; margin:0px; padding:0px"> 复制代码</td> </tr> <tr> <td colspan="2" style="color:rgb(0,0,0); list-style:none; margin:0px; padding:10px"> +----+-------------------+ <br> | id | name | <br> +----+-------------------+ <br> | 1 | sdfsfactsldjfsld | <br> | 2 | sdfsfactsldjfsld | <br> | 3 | sdfsfactsldjfsld | <br> | 4 | sdfsfactsldjfsld | <br> +----+-------------------+</td> </tr> </tbody> </table> 下面描述下,所用到的函数: locate: LOCATE(substr,str) POSITION(substr IN str) 返回子串 substr 在字符串 str 中第一次出现的位置。如果子串 substr 在 str 中不存在,返回值为 0: substring SUBSTR(str,pos,len): 由<str>中的第<pos>位置开始,选出接下去的<len>个字元。 replace replace(str1, str2, str3): 在字串 str1 中,? str2 出??r,?⑵湟 str3 替代。 缺点:只能唯一出现一次<contact>到</contact>,出现多次只能多分成多次替换了 [Link 1]: http://www.111cn.net/list-55/
还没有评论,来说两句吧...