How to check string quotes in regex -
in app can accept strings format:
'key':'value' 'key1':'value1' 'key2':'value2' now want write regex pattern check format write pattern:
/^'(.*)'(:{1})'(.*)?'($|\n)/gm https://regex101.com/r/om1qo9/3
this pattern work if change string below example, work again because select first quote , last quote , string match pattern.
'key':'value','key1':'value1' 'key2':'value2'
the .* pattern matches 0+ chars other line break chars many possible: form current position end of line, consuming ' chars finds on way line end. if use .*? pattern, lazy quantified dot, still go through ' find valid match (a whole line @ least 4 ' chars).
so, need use negated character class here, [^'] matches char '.
/^'([^']*)':'([^']*)'$/ or - disallow empty key names:
/^'([^']+)':'([^']*)'$/ or - disallow both empty names , values:
/^'([^']+)':'([^']+)'$/ details
^- start of string'- apostrophe([^']*)- group 1: 0+ chars other'':'- literal substring':'([^']*)- group 2: 0+ chars other''$-'@ end of string.
see regex demo.
note * matches 0 or more occurrences. if need match @ least one, use + instead.
to allow optional whitespaces, add \s* everywhere needed. e.g., may use
/^\s*'([^']*)'\s*:\s*'([^']*)'\s*$/ see this regex demo.
Comments
Post a Comment