0

This would be ok: 'AAAAAAA1222222' This would be not ok: '1AAAAA' This would not be ok: 'AA1AA'

Just looking for a way to check if a string is ALL letters and then ONLY letters afterward.

6 Answers 6

1

This is an easy one.

^[A-Za-z]*[0-9]*$

That of course is assuming that no letters is OK.

For example, the above example would match

AAAAAAA
2222222

as well as an empty string.

If there must be at least one letter and at least one number, replace the * with +

^[A-Za-z]+[0-9]+$
Sign up to request clarification or add additional context in comments.

Comments

0
text.match(/^[A-Z]*\d*$/i)

Read this as "start of string followed by any number of letters followed by any number of digits followed by the end of the string."

Note this will match "", "A", and "1". If you want there to be at least one letter and at least one number, use + instead of * in both spots.

Comments

0

Use a lookahead. Lookaheads are used for validation, I suggest you go through this.

Try this out: ^(?=[A-Za-z]*\d*$).+

DEMO

3 Comments

I downvoted it, because at the time you just said "Use a lookahead" (which isn't needed for something this simple), and didn't provide an example. Because you've now provided a working example, I've undone my downvote.
I stil don't understand why you would use a lookahead for this.
Oh. Well, it's just that I've read that it's a good practice to use a lookahead whenever there is some sort of validation involved: to check if a password contains all the required, validating an email ID etc and only if it's valid, begin the match. So I posted the original reply since this seemed like something that requires validation. Though, I realise this may seem a bit too complicated for the OP.
0

try this regex

  \b\D+\d+\b 

\b is the word boundary that won't allow for digits to come in the beginning and letters to come after the digits at the end.

Comments

0

I suggest something like this:

text.match(/\b\D+\d+[^\D]\b/);

The \b was suggested by Grace and is a good idea. Another option is to use the beginning and end anchors like:

text.match(/^\D+\d+[^\D]$/);

Comments

0
text.match(/^[a-zA-Z]+\d*$/);

Tests:

AAAAAAA1222222    -    match
1AAAAA            -    no match
AA1AA             -    no match
AAAAAAA           -    match
2222222           -    no match   

If you dont want to match ALL Letters and at least one number change the quantifier of \d from +(1-infinite times) to *(0-infinity times)

more about regex quantifiers : link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.