1

How to specify ] symbol inside character class (MS SQL SERVER PATINDEX function)?

'%["[]%' - for starting bracket - it works
'%["]]%' - for ending - it does not
wUser
  • 23
  • 4
  • 4
    Possible duplicate of [SQL Server LIKE containing bracket characters](https://stackoverflow.com/questions/3661125/sql-server-like-containing-bracket-characters) – snipsnipsnip Sep 04 '18 at 07:07
  • PATINDEX can not be used with ESCAPE keyword as it can with LIKE. – wUser Sep 04 '18 at 07:57
  • You're right. Does [this DBA.SE Question](https://dba.stackexchange.com/questions/206481/matching-a-closing-square-bracket-with-patindex-using-the-wildcard) about closing square bracket help? You might find some workaround there. – snipsnipsnip Sep 05 '18 at 01:17

2 Answers2

0

Looks like there is no way to properly escape closing bracket (]) in PATINDEX. ] alone can be written verbatim, but cannot be included in the character set.

However, according to this DBA.SE question, there are some workaround (see the linked article for the full example):

  1. Specify character range that contains ]. (note that this will match unwanted characters)
PATINDEX('%[[-^{}:,]%' COLLATE Latin1_General_BIN2, MyJSONString)
  1. Apply REPLACE before match.
PATINDEX('%[[' + CHAR(174) + '@]%', REPLACE(@test,']',CHAR(174)))
  1. Use PATINDEX twice: one for ], and the other for the rest of characters.
(NULLIF(PATINDEX('%[[{}:,]%', d.ResponseJSON), 0), NULLIF(PATINDEX('%]%', d.ResponseJSON), 0)))
snipsnipsnip
  • 2,268
  • 2
  • 33
  • 34
  • No. 1 seems be the one i am looking for. No. 2 cannot be as a workaround. In JSON could be symbol ] as text, not as array closing bracket. No. 3 searches two times. – wUser Sep 05 '18 at 06:45
0

After testing different options, this seemed to work as expected. Give it a try.

PATINDEX('%[^]]%', 'test[test]') +1

The "+1" is added because in every test I performed it always stopped one character before the ending bracket "]", this makes sure to capture open and closing positions.

Give it a try, let me know what you think.

Goku
  • 197
  • 1
  • 7