简体   繁体   中英

Combine regular expression together in OR?

I'm testing if input class="k" contains valid characters for the HTML ID attribute, showing an alert if not:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

I'd like to combine both regular expression in logical OR. Is there a way to combine them in a single regex?

$('.k').keyup(function(){
   if((/^[\d]/).test($(this).val())) alert('Not valid!');
   if((/[\s]/).test($(this).val()))  alert('Not valid!');
});

The pipe is the logical OR in a RegEx. In this case, parens are not necessary. However, usually, you want to group the subpatterns:

/(^\d|\s)/

The pattern for ID ( \\w = [a-zA-Z0-9_] ):

/^[a-zA-Z][\w:.-]*$/

As you know what an ID or NAME token must match precisely, you could write a regex to match only valid ones as such:

^[A-Za-z]([-\w:.])*$

If the input doesn't match that, you have an invalid match (note: \\w matches digits and the underscore)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM