Sam
Sam

Reputation: 135

Regex expression for start and end with characters in between numbers

I have requirement in javascript where the starting and ending of a word is a Character with in between numbers. e.g. S652354536667U

I tried with pattern

(/[A-Z]\d+[A-Z]$/).test(S652354536667U) // returns true ok
(/[A-Z]\d+[A-Z]$/).test(S65235Y4536667U) // returns true needed false

but it is allowing characters in between like S65235Y4536667U is being accepted.

Any help is appreciated.

Thanks

Upvotes: 0

Views: 1355

Answers (4)

Jobelle
Jobelle

Reputation: 2834

You need to put ^ at the start and $ at the end in the reg ex. Otherwise if the pattern match anywhere else in the input, it will return true

(/^[A-Z]\d+[A-Z]$/).test(S652354536667U) // returns true 
(/^[A-Z]\d+[A-Z]$/).test(S65235Y4536667U) // returns true 

Check the below image. It is without specifying the start position. So, from the character 'Y' matching the reg ex

enter image description here

Below is with the starting position

enter image description here

Upvotes: 0

user6386114
user6386114

Reputation:

You left caret in the beginning.

["S652354536667U", "S65235Y4536667U"].forEach(item => {
    console.log(/^[A-Z]\d+[A-Z]$/.test(item))
})

Upvotes: 2

hakisan_ks
hakisan_ks

Reputation: 46

You are missing the ^. It should be:

^[A-Z]\d*[A-Z]$

You can use this site to quickly test your regex: https://regexr.com/

Upvotes: 1

Jayce444
Jayce444

Reputation: 9073

You need to put a caret at the start of the regex, to indicate the first letter is at the start of the string, i.e.:

^[A-Z]\d+[A-Z]$

Upvotes: 1

Related Questions