问题
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