Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to allow for 1-500 characters

# A-Z, a-z, 0-9, _ in the middle but never starting or ending in a _
# At least 5, no more than 500 characters

/[A-Za-z\d][-A-Za-z\d]{3,498}[A-Za-z\d]/ }

Hello I have the following above. I want to update the rules to allow for 1 character. I tried changing 3 to 1.

    /[A-Za-z\d][-A-Za-z\d]{1,498}[A-Za-z\d]/ }

But this fails.

How can I allow for at minimum 1 character that is A-Z, a-z, or 0-9 but not a dash and maintain the rules listed above?

Thanks

like image 952
AnApprentice Avatar asked Dec 10 '22 05:12

AnApprentice


2 Answers

You can simplify things by using lookaheads to encode each of your rules separately:

/^(?!_)(?!.*_$)\w{1,500}$/

Explanation:

  • (?!_): Doesn't start with an underscore.
  • (?!.*_$): Doesn't end with an underscore.
  • [\w]{1,500}: Contains between 1 to 500 allowed characters.

One advantage is that the minimum and maximum limits (1 and 500) are made very explicit and are easy to change. It's also easy to add some types of new restrictions later without changing the existing code - just add another lookahead that checks that rule.

Here's an example of it working online (changed to 1 to 10 allowed characters instead of 1 to 500, for clarity):

  • rubular
like image 75
Mark Byers Avatar answered Dec 25 '22 15:12

Mark Byers


Match a single alphanumeric character, and optionally match between 0 and 498 alphanumeric chars including a dash, followed by a single alphanumeric character.

/[A-Za-z\d]([-A-Za-z\d]{,498}[A-Za-z\d])?/

Updated to allow _ in the middle part as well:

/[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/

Also, depending on your use case, you might have to surround your regex with \A and \Z which mark the beginning and end of a string, or word boundaries (\b). This would be necessary if you are using this to match (validate) input strings, for example.

Note that if you use Ruby 1.8.7, you have to use {0,498} instead of {,498}.

Update to finally settle this, based on your other question, you have to add the anchors:

/\A[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?\Z/
like image 39
molf Avatar answered Dec 25 '22 16:12

molf