是否有正则表达式检查字符串是否只包含大写字母、小写字母、数字和下划线?
当前回答
这里有很多冗长的内容,我非常反对,所以,我的结论是:
/^\w+$/
\w等价于[A-Za-z0-9_],这就是你想要的(除非我们在混合中引入Unicode)。
使用+量词可以匹配一个或多个字符。如果你也想接受一个空字符串,使用*代替。
其他回答
使用lookhead来做“至少一件”事情。相信我,这要简单得多。
下面是一个需要1-10个字符的例子,至少包含一个数字和一个字母:
^(?=.*\d)(?=.*[A-Za-z])[A-Za-z0-9]{1,10}$
注意:我本可以使用\w,但随后开始考虑ECMA/Unicode,增加了\w“字字符”的字符覆盖范围。
下面的正则表达式匹配字母数字字符和下划线:
^[a-zA-Z0-9_]+$
例如,在Perl中:
#!/usr/bin/perl -w
my $arg1 = $ARGV[0];
# Check that the string contains *only* one or more alphanumeric chars or underscores
if ($arg1 !~ /^[a-zA-Z0-9_]+$/) {
print "Failed.\n";
} else {
print "Success.\n";
}
这对我很有用。你可以试试:
[\\p{Alnum}_]
要求的格式
允许以下三点:
0142171547295 014 - 2171547295 123年美国广播公司
不允许其他格式:
validatePnrAndTicketNumber(){
let alphaNumericRegex=/^[a-zA-Z0-9]*$/;
let numericRegex=/^[0-9]*$/;
let numericdashRegex=/^(([1-9]{3})\-?([0-9]{10}))$/;
this.currBookingRefValue = this.requestForm.controls["bookingReference"].value;
if(this.currBookingRefValue.length == 14 && this.currBookingRefValue.match(numericdashRegex)){
this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
}else if(this.currBookingRefValue.length ==6 && this.currBookingRefValue.match(alphaNumericRegex)){
this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
}else if(this.currBookingRefValue.length ==13 && this.currBookingRefValue.match(numericRegex) ){
this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
}else{
this.requestForm.controls["bookingReference"].setErrors({'pattern': true});
}
}
<input name="booking_reference" type="text" [class.input-not-empty]="bookingRef.value"
class="glyph-input form-control floating-label-input" id="bookings_bookingReference"
value="" maxlength="14" aria-required="true" role="textbox" #bookingRef
formControlName="bookingReference" (focus)="resetMessageField()" (blur)="validatePnrAndTicketNumber()"/>
虽然它比\w更啰嗦,但我个人很欣赏完整POSIX字符类名称的可读性(http://www.zytrax.com/tech/web/regex.htm#special),所以我会说:
^[[:alnum:]_]+$
然而,虽然上面链接的文档声明\w将“匹配0 - 9,A - Z和A - Z范围内的任何字符(相当于POSIX [:alnum:])”,我还没有发现这是真的。至少不是用grep -P。如果使用[:alnum:],则需要显式地包含下划线,但如果使用\w则不需要。下面的简短而甜蜜的句子是最好不过的:
^\w+$
除了可读性之外,使用POSIX字符类(http://www.regular-expressions.info/posixbrackets.html)意味着正则表达式可以处理非ASCII字符串,而基于范围的正则表达式不会这样做,因为它们依赖于ASCII字符的底层顺序,这可能与其他字符集不同,因此会排除一些您可能想要捕获的非ASCII字符(如字母)。
推荐文章
- 如何从JavaScript中使用正则表达式的字符串中剥离所有标点符号?
- 正则表达式中的单词边界是什么?
- 如何将一个标题转换为jQuery的URL段塞?
- Javascript和regex:分割字符串并保留分隔符
- (grep)正则表达式匹配非ascii字符?
- 如何在保持原始字符串的同时对字符串执行Perl替换?
- 创建正则表达式匹配数组
- *的区别是什么?和。*正则表达式?
- 如何将“camelCase”转换为“Camel Case”?
- 在Java中使用正则表达式提取值
- Java中的正则表达式命名组
- 使用正则表达式搜索和替换Visual Studio代码
- 使用split("|")按管道符号拆分Java字符串
- 替换字符串中第一次出现的模式
- “\d”在正则表达式中是数字吗?