是否有正则表达式检查字符串是否只包含大写字母、小写字母、数字和下划线?


当前回答

Use

^([A-Za-z]|[0-9]|_)+$

...如果你想要明确,或者:

^\w+$

...如果您更喜欢简洁(Perl语法)。

其他回答

这里有很多冗长的内容,我非常反对,所以,我的结论是:

/^\w+$/

\w等价于[A-Za-z0-9_],这就是你想要的(除非我们在混合中引入Unicode)。

使用+量词可以匹配一个或多个字符。如果你也想接受一个空字符串,使用*代替。

要求的格式

允许以下三点:

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()"/>

Use

^([A-Za-z]|[0-9]|_)+$

...如果你想要明确,或者:

^\w+$

...如果您更喜欢简洁(Perl语法)。

我相信您在匹配中没有使用拉丁字符和Unicode字符。

例如,如果需要使用“ã”或“ü”字符,则使用“\w”将不起作用。

你也可以使用这种方法:

^[A-ZÀ-Ýa-zà-ý0-9_]+$

下面是一个正则表达式,用于使用量词指定至少1个字符且不超过255个字符

[^a-zA-Z0-9 _]{1,255}