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


当前回答

要求的格式

允许以下三点:

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

其他回答

对于那些寻找unicode字母数字匹配的人,你可能想做一些类似的事情:

^[\p{L} \p{Nd}_]+$

进一步的阅读请参阅Unicode正则表达式(Unicode Consortium)和Unicode正则表达式(Regular-Expressions.info)。

使用lookhead来做“至少一件”事情。相信我,这要简单得多。

下面是一个需要1-10个字符的例子,至少包含一个数字和一个字母:

^(?=.*\d)(?=.*[A-Za-z])[A-Za-z0-9]{1,10}$

注意:我本可以使用\w,但随后开始考虑ECMA/Unicode,增加了\w“字字符”的字符覆盖范围。

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

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

你也可以使用这种方法:

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

你想要检查每个字符是否符合你的要求,这就是为什么我们使用:

[A-Za-z0-9_]

你甚至可以用简写的形式:

\w

这是等价的(在某些正则表达式中,所以在使用它之前一定要检查一下)。然后,为了表明整个字符串必须匹配,您使用:

^

若要指示字符串必须以该字符开头,则使用

$

若要指示字符串必须以该字符结束。然后使用

\w+ or \w*

表示“1或多个”,或“0或多个”。综上所述,我们有:

^\w*$

^\w*$将适用于以下组合:

1
123
1av
pRo
av1