1

Here is my regex ^((\{.+:.+\})|([^{:}]))+?$.

Here is what i want:
Valid case: {test:test1} {test2:test3} test4 test5.
Invalid case: {test:}, {test1: test2, test1: test3}.

It's mean whenever my string have one of this three character: '{' ':', '}' it must also have 2 remaning character.

My regex is working well when my string not end with } character. I guess it's because of greedy quantifier. But i already put ? character after + quantifier it's still not working. What am I doing wrong?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Thanh Phong
  • 33
  • 1
  • 5

1 Answers1

1

You may use

^(?:\{[^{}:]*:[^:{}]*}|[^{:}])+$

See the regex demo.

Details

  • ^ - start of string
  • (?:\{[^{}:]*:[^:{}]*}|[^{:}])+ - a non-capturing group matching 1 or more occurrences of
    • \{[^{}:]*:[^:{}]*} - a {, then any 0+ chars other than {, } and :, then :, then any 0+ chars other than {, } and :, and a }
    • | - or
    • [^{:}] - any char but {, } and :
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563