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


当前回答

在计算机科学中,字母数字值通常意味着第一个字符不是数字,而是字母或下划线。后面的字符可以是0-9、A-Z、A-Z或下划线。

你可以这样做:

在PHP下测试:

$regex = '/^[A-Za-z_][A-Za-z\d_]*$/'

或者采取

^[A-Za-z_][A-Za-z\d_]*$

并将其放在您的开发语言中。

其他回答

要求的格式

允许以下三点:

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*$将适用于以下组合:

1
123
1av
pRo
av1

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

[\\p{Alnum}_]

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

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

我的意思是,

abcd       True
abcd12     True
ab12cd     True
12abcd     True

1234       False

解释

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

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

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