javascript regex matching 3 digits and 3 letters

五迷三道 提交于 2019-12-30 00:53:07

问题


How to match word in string that contain exactly "3 digits and 3 letters"?

e.g. 100BLA

var regex = ?;
var string = "word word 100BLA word";
desiredString = string .match(regex);

回答1:


\d matches a digit

[a-zA-Z] matches a letter

{3} is the quantifier that matches exactly 3 repetitions

^ Anchor to match the start of the string

$ Anchor to match the end of the string

So if you use all this new knowledge, you will come to a regex like this:

^\d{3}[a-zA-Z]{3}$

Update:

Since the input example has changed after I wrote my answer, here the update:

If your word is part of a larger string, you don't need the anchors ^ and $ instead you have to use word boundaries \b.

\b\d{3}[a-zA-Z]{3}\b



回答2:


INITIAL (incomplete)

var regex = /[0-9]{3}[A-Za-z]{3}/;

EDIT 1 (incomplete)

var regex = /[0-9]{3}[A-Za-z]{3}\b/; // used \b for word boundary

EDIT 2 (correct)

var regex = /\b[0-9]{3}[A-Za-z]{3}\b/; // used \b at start and end for whole word boundary


来源:https://stackoverflow.com/questions/16275661/javascript-regex-matching-3-digits-and-3-letters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!