Home > Net >  Regex to check if all the field is within brackets
Regex to check if all the field is within brackets

Time:09-25

I am trying to develop an if statement that will check if all of the text is within brackets. I am doing this within a postgres DB (plpgsql function) so I was trying to use regexp_replace and doing a length check but I am struggling.

So far, I have this:

if length(regexp_replace((substring(word from '(. )\(')), '\s ', '', 'g'))>0 then

This checks to see if the text in brackets has any words before the brackets, and I have something similar to check if there are words after the brackets.

Is there any way to do this better? Ie, possibly check to see if the entire word is within brackets and there is nothing else outside the brackets?

CodePudding user response:

Yes, this regexp match expression is simpler.
Check if word is a bracketed string w/o non-whitespace characters out of the brackets.

if word ~ '^\s*\(.*\)\s*$' then
-- your code here 
end if;

Edit
Then try

if substring(word from '(?:^|[^\(])\m([\w ] )\M(?:^|[^\)])') is null then
-- your code here 
end if;

The substring expression shall return the non-bracketed word if any.

  • Related