简体   繁体   English

以数字之间的字符开头和结尾的正则表达式

[英]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.我在 javascript 中有要求,其中单词的开头和结尾是数字之间的字符。 eg S652354536667U例如 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.但它允许像 S65235Y4536667U 之间的字符被接受。

Any help is appreciated.任何帮助表示赞赏。

Thanks谢谢

You need to put a caret at the start of the regex, to indicate the first letter is at the start of the string, ie:您需要在正则表达式的开头放置一个插入符号,以指示第一个字母位于字符串的开头,即:

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

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/您可以使用此站点快速测试您的正则表达式: https://regexr.com/

You left caret in the beginning.你一开始就离开了插入符号

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

You need to put ^ at the start and $ at the end in the reg ex.您需要在 reg ex 中将 ^ 放在开头,将 $ 放在末尾。 Otherwise if the pattern match anywhere else in the input, it will return true否则,如果模式匹配输入中的其他任何地方,它将返回 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.它没有指定开始 position。 So, from the character 'Y' matching the reg ex所以,从匹配 reg ex 的字符 'Y'

在此处输入图像描述

Below is with the starting position下面是与起始 position

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM