是否有正则表达式检查字符串是否只包含大写字母、小写字母、数字和下划线?
当前回答
要匹配只包含这些字符(或空字符串)的字符串,请尝试
"^[a-zA-Z0-9_]*$"
这适用于。net正则表达式,可能也适用于许多其他语言。
分解一下:
^ : start of string
[ : beginning of character group
a-z : any lowercase letter
A-Z : any uppercase letter
0-9 : any digit
_ : underscore
] : end of character group
* : zero or more of the given characters
$ : end of string
如果不允许使用空字符串,请使用+而不是*。
正如其他人指出的那样,一些正则表达式语言有[a- za - z0 -9_]的速记形式。在. net正则表达式语言中,您可以打开ECMAScript行为并使用\w作为简写(生成^\w*$或^\w+$)。请注意,在其他语言中,以及在. net中默认情况下,\w范围更广,也会匹配其他类型的Unicode字符(感谢Jan指出这一点)。因此,如果您真的打算只匹配这些字符,那么使用显式(较长的)形式可能是最好的。
其他回答
你想要检查每个字符是否符合你的要求,这就是为什么我们使用:
[A-Za-z0-9_]
你甚至可以用简写的形式:
\w
这是等价的(在某些正则表达式中,所以在使用它之前一定要检查一下)。然后,为了表明整个字符串必须匹配,您使用:
^
若要指示字符串必须以该字符开头,则使用
$
若要指示字符串必须以该字符结束。然后使用
\w+ or \w*
表示“1或多个”,或“0或多个”。综上所述,我们有:
^\w*$
这在大多数情况下都是可行的。
/^[\d]*[a-z_][a-z\d_]*$/gi
我的意思是,
abcd True
abcd12 True
ab12cd True
12abcd True
1234 False
解释
^……$ -匹配模式的开始和结束 [\d]* -匹配零或多个数字 [a-z_] -匹配字母或下划线 [a-z\d_]* -匹配字母、数字或下划线 /gi -全局匹配字符串,不区分大小写
Use
^([A-Za-z]|[0-9]|_)+$
...如果你想要明确,或者:
^\w+$
...如果您更喜欢简洁(Perl语法)。
要求的格式
允许以下三点:
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()"/>
对我来说,有一个问题,我想要区分alpha,数值和alpha数值,所以要确保一个字母数字字符串包含至少一个alpha和至少一个数值,我使用:
^([a-zA-Z_]{1,}\d{1,})+|(\d{1,}[a-zA-Z_]{1,})+$
推荐文章
- 如何从JavaScript中使用正则表达式的字符串中剥离所有标点符号?
- 正则表达式中的单词边界是什么?
- 如何将一个标题转换为jQuery的URL段塞?
- Javascript和regex:分割字符串并保留分隔符
- (grep)正则表达式匹配非ascii字符?
- 如何在保持原始字符串的同时对字符串执行Perl替换?
- 创建正则表达式匹配数组
- *的区别是什么?和。*正则表达式?
- 如何将“camelCase”转换为“Camel Case”?
- 在Java中使用正则表达式提取值
- Java中的正则表达式命名组
- 使用正则表达式搜索和替换Visual Studio代码
- 使用split("|")按管道符号拆分Java字符串
- 替换字符串中第一次出现的模式
- “\d”在正则表达式中是数字吗?