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


当前回答

要求的格式

允许以下三点:

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

其他回答

这对我很有用。你可以试试:

[\\p{Alnum}_]

要匹配只包含这些字符(或空字符串)的字符串,请尝试

"^[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_]+$

这对我很有用。我在O'Reilly的“精通正则表达式”中发现了这个:

/^\w+$/

解释:

^声明字符串开始的位置 \w+匹配任何单词字符(等于[a-zA-Z0-9_]) “+”量词-在一次和无限次之间进行匹配,尽可能多地进行匹配,根据需要进行回馈(贪婪) $在字符串的末尾断言位置

验证自己:

Const regex = /^\w+$/ Const STR = ' nut_cracker_12 '; 让米; If ((m = regex.exec(str)) !== null) { //结果可以通过' m '变量访问。 m.forEach((match, groupIndex) => { console.log('找到匹配,组${groupIndex}: ${match} '); }); }

对于Java,只允许不区分大小写的字母数字和下划线。

^匹配以任何字符开头的字符串 [a-zA-Z0-9_]+匹配字母数字字符和下划线。 $匹配以0或多个字符结尾的字符串。 公共类RegExTest { public static void main(String[] args) { System.out.println(“_C #”.matches (" ^ [a-zA-Z0-9_] + $ ")); } }