SQL Query to include/exclude characters - mysql

I have a dictionary table 'dictionary', where column 'word' contains the list of all English words.
I want to find all words that contain specific alphabet characters only and exclude the rest of the alphabet. I am able to do so (see the example below), but as you can see, it is downright ugly.
EXAMPLE
Currently to find all words that contain letters 'a', 'b', 'c', 'x', 'y', 'z', but exlude rest of the alphabet letters I do this:
SELECT word
FROM dictionary
WHERE (
word LIKE '%a%'
OR word LIKE '%b%'
OR word LIKE '%c%'
OR word LIKE '%x%'
OR word LIKE '%y%'
OR word LIKE '%z%'
) AND (
word NOT LIKE '%d%'
AND word NOT LIKE '%e%'
AND word NOT LIKE '%f%'
AND word NOT LIKE '%g%'
AND word NOT LIKE '%h%'
AND word NOT LIKE '%i%'
AND word NOT LIKE '%j%'
AND word NOT LIKE '%k%'
AND word NOT LIKE '%l%'
AND word NOT LIKE '%m%'
AND word NOT LIKE '%n%'
AND word NOT LIKE '%o%'
AND word NOT LIKE '%p%'
AND word NOT LIKE '%q%'
AND word NOT LIKE '%r%'
AND word NOT LIKE '%s%'
AND word NOT LIKE '%t%'
AND word NOT LIKE '%u%'
AND word NOT LIKE '%v%'
AND word NOT LIKE '%w%' )
Any way to accomplish this task using some form of regex or other optimization?
Any tricks or hints would be much appreciated.

You can achieve it using REGEXP
SELECT `word `
FROM `dictionary`
WHERE `word` REGEXP '[abcxyzABCXYZ]'
AND `word` NOT REGEXP '[defghijklmnopqrstuvwDEFGHIJKLMNOPQRSTUVW]'

This is a better approach.
SELECT word
FROM dictionary
WHERE word REGEXP '.*[abcxyzABCXYZ].*$'
AND word NOT REGEXP '.*[defghijklmnopqrstuvwDEFGHIJKLMNOPQRSTUVW].*$';

Check This.
set #1='a'\\
set #2 ='b'\\
set #3 ='c'\\
set #4 ='x'\\
set #5 ='y'\\
set #6 ='z'\\
set #find=CONCAT(#1,#2,#3,#4,#5,#6)\\
set #ALl='abcxyzdefghijklmnopqrstuvw'\\ all alphabets here
set #ALl=replace(#ALl,#1,'')\\ replace alphabet that you want
set #ALl=replace(#ALl,#2,'')\\
set #ALl=replace(#ALl,#3,'')\\
set #ALl=replace(#ALl,#4,'')\\
set #ALl=replace(#ALl,#5,'')\\
set #ALl=replace(#ALl,#6,'')\\
SELECT word
FROM dictionary
WHERE word RLIKE CONCAT('.*[',#find,'].*$')
AND word NOT RLIKE CONCAT('.*[',#ALl,'].*$');\\
Check Demo Here

If you can't use REGEXP for some reason, then this should work too:
SELECT word
FROM dictionary
WHERE Replace(Replace(Replace(Replace(Replace(Replace(
word, 'a', ''),
'b', ''),
'c', ''),
'x', ''),
'y', ''),
'z', '') = ''
I doubt it will be very fast though. Then again, I'm not sure anything will be fast for this requirement =)

The test is simply:
word REGEXP '^[abcxyz]*$'
That says that everything from start (^) to end ($) must be a string of zero or more (*) of the characters ([]) abcxyz.
I did not include both lower and upper case on the presumption that you are using a case-insensitive collation.
There is no need for the AND .. NOT.
There is a possible problem: If you want to allow notw, do you want to match won't? That is, what should be done about punctuation?
(There may be other edge cases that are not adequately specified in the Question.)

WHERE Field not LIKE '%[^a-z0-9 .]%'

Related

How to ignore symbols in SQL LIKE

I have a search module with SQL query like this:
SELECT FROM trilers WHERE title '%something%'
And when I search for keyword for example like "spiderman" it returns not found, but when I search for "spider-man" it returns my content (original row in MySQL is "spider-man").
How can I ignore all symbols like -, #, !, : and return content with "spiderman" and "spider-man" keywords at the same time?
What you can do is replace the characters you don't care about before the search takes place.
First iteration would look like this:
SELECT * FROM trilers WHERE REPLACE(title, '-', '') LIKE '%spiderman%'
This would ignore any '-'.
Next you would rap that with another REPLACE to include '#' like this:
SELECT * FROM trilers WHERE REPLACE(REPLACE(title, '-', ''), '#', '') LIKE '%spiderman%'
For all 3 ('!','-','#') you would just increase the Replace with another Replace like this:
SELECT * FROM trilers WHERE REPLACE(REPLACE(REPLACE(title, '-', ''), '#', ''),'!','') LIKE '%spiderman%'
You could try something like
SELECT * FROM trilers WHERE replace(title, '-', '') LIKE '%spiderman%'
The other answers involving using REPLACE are great, but if you don't care what characters appear between "spider" and "man" or how many characters there are between the two strings, you can use an additional wildcard in your expression:
SELECT * FROM Superheroes WHERE HeroName LIKE '%spider%man%';
If you want to match only one character, but allow any character, you can use the _ wildcard, which matches only one character:
SELECT * FROM Superheroes WHERE HeroName LIKE '%spider_man%';
This will match "spideryman" and "spideryman in la la land" but not "spiderysupereliteuberheroman".
If you have a limited number of possible symbols, a way to do it without REPLACE is to use a disjunctive expression:
SELECT * FROM Superheroes WHERE
HeroName LIKE '%spiderman%'
OR
HeroName LIKE '%spider-man%'
OR
HeroName LIKE '%spider#man%'
OR
HeroName LIKE '%spider!man%';
WHERE trilers REGEXP '[[:<:]]spider[-#!:]?man[[:>:]]'
Some discussion:
[[:<:]] -- word boundary
[-#!:] -- character set, matches any of them. ('-' must be first)
[-#!:]? -- optional -- so that 'spiderman' will still match
This, unlike the rest of the answers, will avoid matching
spidermaniac
Also, consider using FULLTEXT.
You should be able to use your search with a small update. You should be able to do something like: SELECT FROM trilers WHERE title LIKE '%spider%'. This should search for anything where spider is before or after something else like the hyphen (-)

SELECT to match special characters and case

Field X in table may contain special characters e.g hello!World and I would like to know if there is a way to match that with HelloWorld (Ignore case and special characters).
SELECT * FROM table WHERE X='Helloworld'
http://sqlfiddle.com/#!9/2afa1/1
if you need exaclty match of string:
SELECT *
FROM table1
WHERE x REGEXP '^hello[[:punct:],[:space:]]world$';
And if hello world could be a part of larger string:
SELECT *
FROM table1
WHERE x REGEXP 'hello[[:punct:],[:space:]]world';
What you can do is to replace all special characters like this:
SELECT * FROM table WHERE LOWER(REPLACE(X, '!', '')) = LOWER('HelloWorld');
Chain those replacements if you have to replace more:
SELECT * FROM table WHERE LOWER(REPLACE(REPLACE(X, '!', ''), '?', '')) = LOWER('HelloWorld');
If I understood your question right, you need to filter out non-ASCII characters? Please confirm whether this is true. In order to do that, have a look at REGEXP matching as in the comment link and this question.
Try something like
SELECT * FROM `table ` WHERE `X` REGEXP 'Helloworld';
REGEXP 'hello[^[:alpha:]]*world'
Notes:
This finds the string in the middle of other stuff; add ^ and $ to anchor to ends.
This assumes the non-alpha character(s) are between hello and world, not some other spot in the string.
This relies on the relevant collation to do (or not do) case folding.

REGEXP in mysql

I have a database of all english language words. I want to find regular expression for particular alphabets. like for example if i ask for the regular expression for "eta", it should return all the words who have 'e','a' and 't' in any combination. but when I run the following code
SELECT word FROM wordlist
WHERE
word REGEXP 'eta';
it return words like 'beta,caretake,detach etc....'
how to use regexp in its true spirit in mysql.
Thanks in Advance
SELECT word
FROM wordlist
WHERE word REGEXP 'e'
AND word REGEXP 'a'
AND word REFEXP 't'
Try:
SELECT word FROM wordlist WHERE word REGEXP '(e|t|a)'

Regexp for a string

I want a regular expression to match all strings like 'T' OR 'T-Th' but NOT values containing only 'Th'
my current regexp is this one:
REGEXP = '[T-Th]'
but it matches all strings 'T' , 'T-Th' and 'Th' which 'Th' is not desirable
REGEXP = '(T-Th|T[^h])'
We either match T-Th literally, OR match T that is not followed by anything but an h. In other words: T, T-Th, but not Th.
Regex101
If I have the logic correct, you want a 'T' in the string and you want a 'T' not followed by 'h':
where col like '%T%' and
replace(col, 'Th', '') like '%T%'
The - character between brackets is special for regex. It must be escaped when the use is literal. A good alternative for your problem could be this:
REGEXP = '(T-Th|T(?!h))'

In Mysql get rows that have a field that ends in space and one character

I'm trying to get all rows where the field given name ends in a space and a letter, any letter. Currently the SQL I have is
SELECT person_id FROM person_name
WHERE given_name LIKE '% M'
OR given_name LIKE '% C'
OR given_name LIKE '% A'
but instead of enumerating out all the letters I would like a query that is
given_name like '% X' where X is any letter (upper and lower case).
I tried regexp [a-zA-Z] but couldn't figure out how to tell regexp that it was the last two characters in the string. Any ideas?
I think you'd want
SELECT * FROM `person_name` WHERE `given_name` REGEX " [a-zA-Z]$"
The $ signals the end of the string.
Try something like this:
SELECT `given_name`
FROM table
WHERE `given_name` like '% _'
Try
REGEXP '[a-zA-Z]$'
$ should match the end of the string.
See http://dev.mysql.com/doc/refman/5.1/en/regexp.html for details.