Suppose I have a string with comma-separated entries "el1, el2, el3", the regular expression for this string is [\ w] +, [\ w] *. How to write an expression for the same string but with the check that only one element in the beginning has the string "primary key"?

  • one
    not quite clear question. Show me an example so that you can make a start. a few lines and the desired result - DiGiTAL
  • "PK el1, el2, el3" - TRUE - one element with the string PK. "PK el1, PK el2, el3" - FALSE - more than one element with a PK line. "el1, el2, el3" - FALSE - no elements with the string PK. - Naum Ochkus

1 answer 1

^(?=.*PK\s+\w)((PK\s(?!.*PK\s+\w))?\s*\w+\s*(,|$))+$ 

Test at regex101.com

 ^ # Начало строки (?=.*PK\s+\w) # Где то в строке должен быть PK с пробелом и буквой после него ( # Начало группы описывающий элемент списка (PK\s(?!.*PK\s+\w))? # Может быть PK. Если есть - то после него нигде PK больше нет \s*\w+\s* # прочие буквы и пробелы (,|$) # после них или запятая или конец строки )+ # группа должна повторятся 1 и более раз $ # конец строки