AnApprentice
AnApprentice

Reputation: 110970

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

Upvotes: 4

Views: 1414

Answers (3)

Mark Byers
Mark Byers

Reputation: 838376

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):

Upvotes: 9

molf
molf

Reputation: 74955

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/

Upvotes: 4

eykanal
eykanal

Reputation: 27027

/^[A-Za-z\d]([-A-Za-z\d]{0,498}[A-Za-z\d])?$/
  1. Make the whole second part optional (with the parenthesis ending with a ?)
  2. Within the second part, make the middle part optional (using the {0,<number>} construct, which doesn't specify a lower limit)

Upvotes: 1

Related Questions