MySQL substring match using regular expression; substring contain 'man' not 'woman'

萝らか妹 提交于 2021-02-10 04:14:17

问题


I have an issue while I fetch data from database using regular expression. While I search for 'man' in tags it returns tags contains 'woman' too; because its substring.

SELECT '#hellowomanclothing' REGEXP '^(.)*[^wo]man(.)*$'; # returns 0 correct, it contains 'woman'
SELECT '#helloowmanclothing' REGEXP '^(.)*[^wo]man(.)*$'; # returns 0 incorrect, it can contain anything other than 'woman' 
SELECT '#stylemanclothing' REGEXP '^(.)*[^wo]man(.)*$'; # returns 1 correct

How can I update the regular expression, when I search for 'man' it should return only the tag contains 'man' not 'woman'?


回答1:


A variant of n-dru pattern since you don't need to describe all the string:

SELECT '#hellowomanclothing' REGEXP '(^#.|[^o]|[^w]o)man';

Note: if a tag contains 'man' and 'woman' this pattern will return 1. If you don't want that Gordon Linoff solution is what you are looking for.




回答2:


You can use two expressions. I think like is sufficient:

SELECT ('#stylemanclothing' like '%man%' and '#stylemanclothing' not like '%woman%')

Although you can express this in a regular expression, this is probably the easier solution.




回答3:


Use this:

SELECT '#helloowmanclothing' REGEXP '^(.)*([^o]|[^w]o)man(.)*$'

In your pattern [^wo] stands for "one character except for w and o", while you need to exclude two consecutive characters - w and then o.

Therefore above pattern allows for o before man only if o is preceeded by character other than w.



来源:https://stackoverflow.com/questions/30978637/mysql-substring-match-using-regular-expression-substring-contain-man-not-wom

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!