How to create this regular expression?

Asked

Viewed 1,829 times

0

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

Rules

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

Examples

  1. [First-Example]
  2. [Second-Example-Valid]
  3. [3-Example-Valid]
  4. [Event-4]
  • What programming language are you using?

  • I am using c#, but I intend to use also in PHP @Sergio

  • 1

    In the beginning this should give, test https://regex101.com/r/zQ1oD5/1 If this is the case I can add an answer to explain.

  • It’s great, just a detail I forgot to comment on, I even updated the question: the first and last character inside the brackets can’t be the trace. And also the content inside the brackets can not just be numbers. But it’s great, if you want to explain, already mark as solved @Sergio :)

  • Is there any rule of how many - there are in every string?

  • No, the - will only be for word separation if the user wishes. But it is not required as it may contain things like [Valid] @Sergio

Show 1 more comment

1 answer

5


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

What the regex does:

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

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

(online example)

  • 1

    Excellent, that’s what I needed. Thank you very much, Sergio!

  • @Zackmorgan great! I’m glad I helped.

  • @Sergio just remembering that these regex do not contemplate the second requirement. Otherwise the answer this great :D

  • @Guilhermelautert well seen, had only checked the end of the string. I corrected, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.