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


当前回答

要求的格式

允许以下三点:

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+$/

\w等价于[A-Za-z0-9_],这就是你想要的(除非我们在混合中引入Unicode)。

使用+量词可以匹配一个或多个字符。如果你也想接受一个空字符串,使用*代替。

Use

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

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

^\w+$

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

这对我很有用。我在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} '); }); }

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

你可以这样做:

在PHP下测试:

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

或者采取

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

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

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

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

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

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

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

^\w+$

Or

^\w*$