Sneha
Sneha

Reputation: 133

Need to write regular expression in Javascript

Need to write regular expression in javascript on a field with constraint -

The name can be up to 80 characters long. It must begin with a word character, and it must end with a word character or with ''. The name may contain word characters or '.', '-', ''."

Example -

Allowed strings -

abc.'
abc-'.'
ab-.''-a

Not allowed strings -

rish a
rish.-

What I have tried so far:

!/^[A-Za-z.-'']{1,80}$/.test(Name)

Upvotes: 0

Views: 56

Answers (2)

matvs
matvs

Reputation: 1873

Using look-ahead assertion is a very clever way of solving this. Another way would be using OR operator:

^[a-zA-Z]$|^[a-zA-Z][a-zA-Z.\-']{0,78}[a-zA-Z']$

It simply checks whether:

^[a-zA-Z]$ - there is only one word character

Or |

^[a-zA-Z]$ - one word character at the very beginning of given string
[a-zA-Z.\-']{0,78} - from zero to seventy-eight characters. . (dot) does not have to be escaped, since it has no special meaning in character set.
[a-zA-Z'] - one word character or apostrophe

Thus it validates strings longer, than 1 character.

https://regex101.com/r/CB1uOw/1

Upvotes: 0

Christoph Herold
Christoph Herold

Reputation: 1809

I guess, you're looking for something like this:

^(?=[A-Za-z])[A-Za-z\.\-']{0,79}[A-Za-z']$

To explain:

^(?=[A-Za-z]): Check, that the string starts with a word character. This is a look-ahead assertion, so it will NOT take a part in the match. The rest of the pattern must still account for at least 1 and max 80 characters.

[A-Za-z\.\-']{0,79}: First and middle characters, therefore max 79 chars. Minimum of one is enforced with the last character.

[A-Za-z']$: Ends with a letter or apostrophe.

Testable here: https://regex101.com/r/AOQojT/1

Upvotes: 2

Related Questions