monti
monti

Reputation: 455

Simplify Regular Expression with variable amount of alphanumeric character separated by a dash

I would like to validate a specific string to be correct. A correct string looks like the following:

ab1-peter-application

The rules for the string are <1-4 alphanumeric characters>-<1-30 alphanumeric characters>-<1-30 alphanumeric characters>

I just build the regex as following which I guess would work:

[a-zA-Z0-9]{1,4}[-]{1}[a-zA-Z0-9]{1,30}[-]{1}[a-zA-Z0-9]{1,30}

As every segment seems to be the same and the occurrence of the alphanumeric characters vary I feel like it can be shortened. Is there any chance to shorten/simplify this regex?

Upvotes: 0

Views: 91

Answers (2)

Ashish Sapkale
Ashish Sapkale

Reputation: 550

[a-zA-Z0-9]{4}(-[a-zA-Z0-9]{30}){2}$ - simple Regex to match exact length required string.

^[a-zA-Z0-9]{1,4}(-[a-zA-Z0-9]{1,30}){2}$ - simple Regex to match variable length required

Hope this will help

Upvotes: -1

CertainPerformance
CertainPerformance

Reputation: 370779

You can combine the final two parts:

-<1-30 alphanumeric characters>-<1-30 alphanumeric characters>

into a single group, repeated twice. Additionally, a single character in a character set is superfluous - you can remove the character set entirely, in that case, to make the regex more concise. The same is true for {1} (meaningless quantifier):

[a-zA-Z0-9]{1,4}(?:-[a-zA-Z0-9]{1,30}){2}

Additionally, if possible in your environment, use the case-insensitive flag (so you don't have to repeat a-zA-Z) and also use \d to represent digits instead of 0-9:

[a-z\d]{1,4}(?:-[a-z\d]{1,30}){2}

Upvotes: 2

Related Questions