How to create this regular expression?

0

I need a regular expression that accepts only [ , ] , - and letras and números to be used as follows:

Rules

  • The first character is [ , then comes letters numbers and - and ends with ] .
  • The first and last character inside the brackets can not contain - .
  • The content inside the brackets can not be just numbers.

Examples

  • [First Example]
  • [Second-Example-Valid]
  • [3-Example-Valido]
  • [Event-4]
  • asked by anonymous 15.07.2016 / 15:08

    1 answer

    5

    You can use this way: /^\[[\w][\w\-]*[\w]+\]$/
    ( online example )

    What regex does:

    • ^ indicates the beginning of the string
    • \[ indicates the own character [ , escaped not to be interpreted as list
    • [\w]+ accepts numbers and letters. One or more times
    • [\w\-] the same as the previous plus the characters _ and - , zero or multiple times.
    • [\w]+ I put this class back but without \- to ensure that the last character before the ] end is not a - .
    • \] indicates the character ]
    • $ indicates end of string

    If you want to prevent it from having only numbers and the - separator you can check with negative lookahead which in the background is another regex with what is not allowed. In this case it would look like this: /^(?!^\[[\d\-]+\]$)\[[\w][\w\-]*[\w]+\]$/ , where (?!xxx) is what indicates this negative check.

    ( online example )

        
    15.07.2016 / 15:25