[英]How to make regular expression with only 3 characters and 3 digits?
I have tried the below regex for match here http://rubular.com/ but it matches only 3 characters or 3 digits at a time. 我在这里尝试了以下正则表达式匹配http://rubular.com/但它一次只匹配3个字符或3个数字。
^((\d{3})|(\w{3}))$
I need result like this: 我需要这样的结果:
123eee 123eee
4r43fs 4r43fs
Here you go: 干得好:
^(?=(?:[a-z]*\d){3})(?=(?:\d*[a-z]){3})\w{6}$
http://regex101.com/r/hO5jY9 http://regex101.com/r/hO5jY9
If there are at least three digits, at least three letters, and at most six characters, the string has to match. 如果至少有三个数字,至少三个字母,最多六个字符,则该字符串必须匹配。
How does this work? 这是如何运作的?
\\w{6}
until the end of the string 在这些断言之后,我们可以自由地将任何6个字符与\\w{6}
匹配,直到字符串结束 The lookaheads 前瞻
Let's break down the first lookahead: (?=(?:[az]*\\d){3})
让我们分解第一个前瞻: (?=(?:[az]*\\d){3})
It asserts that three times ( {3}
), at this position in the string, which is the start of the string as asserted by ^
, we are able to match any number of letters, followed by a single digit. 它断言三次( {3}
),在字符串中的这个位置,这是由^
断言的字符串的开头,我们能够匹配任意数量的字母,后跟一个数字。 This mean there must be at least three digits. 这意味着必须至少有三位数。
One lookahead should be enough to check, if there are exactly 3 digits: 一个前瞻应该足以检查,如果有正好3位数:
^(?=\D*(?:\d\D*){3}$)[^\W_]{6}$
Used [^\\W_]
as shorthand for [A-Za-z0-9]
. 使用[^\\W_]
作为[A-Za-z0-9]
简写。
If you want to use regex it is quite complicated: 如果你想使用正则表达式,它是非常复杂的:
^(?=.*\d.*\d.*\d)(?=.*[a-zA-Z].*[a-zA-Z].*[a-zA-Z]).{6}$
This will do what you want. 这将做你想要的。
\\w
is not what you want, it also includes \\d
and the underscore "_". \\w
不是你想要的,它还包括\\d
和下划线“_”。
(?=.*\\d.*\\d.*\\d)
is a positive lookahead assertion to check the condition of three digits in the string. (?=.*\\d.*\\d.*\\d)
是一个正向前瞻断言,用于检查字符串中三位数的条件。
(?=.*[a-zA-Z].*[a-zA-Z].*[a-zA-Z])
is a positive lookahead assertion to check the condition of three letters in the string. (?=.*[a-zA-Z].*[a-zA-Z].*[a-zA-Z])
是一个正向先行断言,用于检查字符串中三个字母的状态。
.{6}
checks for a length of 6 overall .{6}
检查总长度为6
function checker(data) {
var splitted = data.split(/\d/);
if (splitted.length === 4) {
return splitted.join("").split(/[a-zA-Z]/).length === 4;
}
return false;
}
console.assert(checker("123eee") === true);
console.assert(checker("4r43fs") === true);
console.assert(checker("abcd12") === false);
console.assert(checker("4444ab") === false);
console.assert(checker("ab1c") === false);
console.assert(checker("444_ab") === false);
如果您只想匹配任何六个字符的数字组合和“单词字符”,请使用:
/^[\d\w]{6}$/
Hi we can do this in two ways. 嗨,我们可以用两种方式做到这一点。
If you need IE7 support " ? " expression will give some issues .So you can check like below. 如果你需要IE7支持“?”表达式会给出一些问题。所以你可以检查如下。
[\d\w]{6} && ![\d]{6} && ![\w]{6}
check for combination 检查组合
check for only digit or not 只检查数字
check for only alphabets. 只检查字母。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.