正则表达式用于匹配字母数字和下划线

803

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


19
不同的正则表达式引擎对于匹配字母数字字符的方法不一样,这真是令人遗憾。像这样的问题(相当模糊,没有指定任何语言/正则表达式风格)需要一个非常长的,或者至少是一个很有组织的答案来详细讲解每种风格的匹配方法。 - Wiktor Stribiżew
21个回答

-1

所需格式

允许以下三种格式:

  1. 0142171547295
  2. 014-2171547295
  3. 123abc

不允许其他格式:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接