遇到的问题:
以下是数据库中的一个表mt2:
代码如下 | 复制代码 |
+----+------------------------------------------+ | id | name | +----+------------------------------------------+ | 1 | sdfsf<contact>beijing</contact>sldjfsld | | 2 | sdfsf<contact>shanghai</contact>sldjfsld | | 3 | sdfsf<contact>jn</contact>sldjfsld | | 4 | sdfsf<contact>qd</contact>sldjfsld | +----+------------------------------------------+ |
遇到的要求是:将该表中<contact>到</contact>的内容删除。
众所周知,replace函数是不支持正则表达式的,所以只能采用其他的方法处理。
于是,我是使用了下面的sql语句:
代码如下 | 复制代码 |
update mt2 set name = replace(name, substring(name, locate('<contact>', name),locate('</contact>', name)-locate('<contact>'+10, name)),''); |
字符串(正则) 模糊
问题解决了。
结果:
代码如下 | 复制代码 |
+----+-------------------+ | id | name | +----+-------------------+ | 1 | sdfsfactsldjfsld | | 2 | sdfsfactsldjfsld | | 3 | sdfsfactsldjfsld | | 4 | sdfsfactsldjfsld | +----+-------------------+ |
下面描述下,所用到的函数:
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>,出现多次只能多分成多次替换了