简体   繁体   中英

Regex to check if field has both numbers and letters

I was just looking for a regex expression to check and see if both numbers and letters exist.

Just to clarify the query, the regex is going to be written in javascript and used to validate an address.

I would use a regular expression which matches any letter followed by any digit (with any possible characters in between) or digit then letter (with anything in between):

var hasNumbersAndLetters = function(str) {
  var regex = /(?:[A-Za-z].*?\d|\d.*?[A-Za-z])/;
  return !!str.match(regex);
};

Much easier to run two checks.

/\pL/ && /\pN/

To do both checks in one pattern, you need something like

/\pL.*\pN|\pN.*\pL/s

Languages supporting zero-width lookaheads can eliminate the redundancy:

/^(?=.*\pL/)(?=.*\pN/)/s    ( or /^(?=.*\pL/).*\pN/s )

But it's harder to read.

Pardon me for not using JS's match function, but the question is really about regular expressions, and I'm not familiar with JS's match function.

if it is a single word you are matching without spaces, with both numbers and letters, it can be assumed they touch somewhere - so if it matches letter then number or number then letter we have a match - so:

([a-zA-Z][0-9]|[0-9][a-zA-Z])


Edit: where there may be spaces then you can use lookahead assertions like this

([a-zA-Z](?=.*[0-9])|[0-9](?=.*[a-zA-Z]))

Saw you wanted to validate an address

Removed by regex answer as javascript has no Unicode support, except for matching single characters http://www.regular-expressions.info/unicode.html

这应该这样做:

^[\w]*[^\W_][\w]*$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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