regex - Rejecting specific regular expression patterns -


i'm new regex , trying match string that

  • can have length
  • can alphanumeric , can contain $, -, or /
  • cannot contain more 2 of these non-alphanumeric characters in row or end / or -.

for example, hello/world valid, hello//world invalid.

i've tried couple different possibilities, 1 coming closest working i'm expecting:

^--|-/|/-|\s\s|$$|$-|-$|$/|/$|//|([a-za-z0-9 -$/])*(?<![/-])$ 

this seems sufficient every scenario except when 2 forward slashes together. forward slashes need escaped, or because matching expression broad , swallowing bad strings? i've tried various other expressions negative look-ahead , look-behind run issues, false negatives.

cheers,

jeff

here regex looking for:

^(?![^/$-]*[/$-]{2})[\w/$-]+(?<![/-])$ 

regex demo , ideone java demo

string str1 = "hello/world"; string str2 = "hello//world"; string ptrn = "^(?![^/$-]*[/$-]{2})[\\w/$-]+(?<![/-])$"; system.out.println(str1.matches(ptrn)); // => true system.out.println(str2.matches(ptrn)); // => false 

explanation:

  • ^ - start of string (unnecessary in matches())
  • (?![^/$-]*[/$-]{2}) - lookahead ensuring string has no more 1 non-alphanumeric character
  • [\w/$-]+ - main character class matching alphanumeric characters , /, $ or -
  • (?<![/-]) - lookbehind making sure string not end forbidden non-alphanumeric characters
  • $ - end of string (unnecessary in matches())

Comments