RegEx to match any character except strings with surrounding prefixes -


i'm trying create regex validate input match character should exclude input surrounded prefixes (i.e. {#..#}, {@..@} or {$..$}).

given example:

free text fine // should return true {#some other text#} // should return false text numbers 671 // should return true {@hello world@} // should return false {$hello mars$} // should return false {$some text not close // should return true 

this should possible use of negative look-around, along lines of:

^(\?!=(\{@[^.]+@\}))(\?!=(\{$[^.]+$\}))(\?!=(\{#[^.]+#\})).* 

any appreciated : )

you syntax bit weird if ask me... suggest:

^(?!\{(?:[$@#]).*(?:[$@#])\}).* 

demo

first 'group' \{(?:[$@#]) looks opening prefix, .* match in middle , (?:[$@#])\} match closing suffix.

note not allow things like:

{$hello mars$} how you? 

if want accept well, add end of line anchor:

^(?!\{(?:[$@#]).*(?:[$@#])\}$).*                             ^ 

demo

you can use character class have different symbols [@$#] , shorter having multiple negative lookarounds or | operators in side :)

edit: prevent things {#free text fine$}' use:

^(?!\{([$@#]).*\1\}).* 

or

^(?!\{([$@#]).*\1\}$).* 

for second version.

\1 backreference , refers first captured group (any of $, @, or #).


Comments