Stephen
Stephen

Reputation: 8218

REGEXP to NOT match if there is a hyphen before a variable

I am having a hard time correctly matching a variable ($myvar) using MySQL REGEX.

My first thought was to match the word (\b), but this will match both "testtype" and "edit-testtype" in my example below, which I don't want:

SELECT "edit-testtype, themes, upload, plugin-editor" REGEXP '\\b$myvar\\b';

After a lot of internet searching I thought I had the answer with this:

SELECT "edit-testtype, themes, upload, plugin-editor" REGEXP '\^(?!-)\\b$myvar\\b';

but it will fail on any of the other words in the string. I guess what I need is a REGEX that will NOT match any $myvar that is preceded by a hyphen/dash.

Upvotes: 1

Views: 766

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

If you want to try a regex way, you may use

REGEXP CONCAT('(^|[^-])[[:<:]]', $myvar', '($|[[:>:]][^-])')

This won't work if your$myvar contains special chars like [, (, + - they would need to be escaped.

Note that (^|[^-]) matches the start of string or a non-hyphen, [[:<:]] matches a leading word boundary and [[:>:]] matches the trailing word boundary.

The ($|[[:>:]][^-]) part matches 2 alternatives: either the end of string ($) or a trailing word boundary plus a character other than a hyphen.

Upvotes: 1

trincot
trincot

Reputation: 350147

You could use this regular expression (example with edit-testtype):

(^|, )edit-testtype(,|$)

But as you are essentially trying to find an element in a comma-separated list, you could use find_in_set:

select find_in_set($myvar, "edit-testtype,themes,upload,plugin-editor") > 0

You just need to make sure not to have spaces after the commas. If you cannot change that, use a plain replace on it:

replace("edit-testtype, themes, upload, plugin-editor", ", ", ",")

... before applying find_in_set().

Upvotes: 0

ThePloki
ThePloki

Reputation: 185

http://regexr.com/3do1b

Try this regex: ^[^-]+$

I haven't tested this.

Upvotes: 1

Related Questions