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


当前回答

这在大多数情况下都是可行的。

/^[\d]*[a-z_][a-z\d_]*$/gi

我的意思是,

abcd       True
abcd12     True
ab12cd     True
12abcd     True

1234       False

解释

^……$ -匹配模式的开始和结束 [\d]* -匹配零或多个数字 [a-z_] -匹配字母或下划线 [a-z\d_]* -匹配字母、数字或下划线 /gi -全局匹配字符串,不区分大小写

其他回答

嗯…问题:它是否至少需要一个字符?它可以是空字符串吗?

^[A-Za-z0-9_]+$

将至少做一个大写或小写字母数字或下划线。如果它的长度可以为零,那么只需用+替换*:

^[A-Za-z0-9_]*$

如果需要包含变音符字符(例如cedilla - ç),那么您将需要使用单词character,其功能与上述相同,但包括变音符字符:

^\w+$

Or

^\w*$

要求的格式

允许以下三点:

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字符(如字母)。

Use

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

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

^\w+$

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

对我来说,有一个问题,我想要区分alpha,数值和alpha数值,所以要确保一个字母数字字符串包含至少一个alpha和至少一个数值,我使用:

^([a-zA-Z_]{1,}\d{1,})+|(\d{1,}[a-zA-Z_]{1,})+$