Keith
Keith

Reputation: 738

Regex to match a custom ID format

I need to check if a string has the following format:

This is my current attempt:

/^([a-z0-9]+[\S]+)?[a-z0-9]+$/ig

I am new to regex. It seems to work, but does it fully satisfy the requirements above? Is there anything else I need to think about?

Upvotes: 1

Views: 3324

Answers (3)

Aaron
Aaron

Reputation: 24802

Here is why your requirements are satisfied :

  • The length must be at least one :

    The end of your regex isn't optional and contains the [a-z0-9]+ tokens which must match at least one alphanumeric character. To check this with complex regexs I would suggest removing every token that is modified by ?, *, {0,}, {,n} or {0,n}, then removing alternations which are left with an empty alternative. If there still are tokens in the regex, it must match at least one character.

  • The first character and last character must be alpha-numeric :

    Either the first character is matched by the optional group or by what follows. Both groups start with at least an occurence of [a-z0-9] which satisfies the condition. You correctly use anchors which assert that this condition does apply to the full string rather than to a subsequence.

  • Any characters between the first and last character can be anything except white space.

    Your regex doesn't accept any whitespace character, it only accepts characters of [a-z0-9\S] which doesn't contain any whitespace character.

Upvotes: 1

Artem Ilchenko
Artem Ilchenko

Reputation: 1035

you need change first and last symbol matching /^[a-z0-9]\S+?[a-z0-9]$/ig

in this expression [a-z0-9] - one alpha-numeric symbol \S+? any non white space symbol

Upvotes: 1

Simo
Simo

Reputation: 195

You can try this :

\b\w([.^\S]*)\w*\b

Upvotes: 1

Related Questions