javascript - How to use the "or" command within JS regEx properly? -
i tried write more or less complex regex js. passes tests except 2 , don't know why. code
function telephonecheck(str) { regex1 = /^[1]\s(\d{3}[-]){2}\d{4}|(\d{3}[-]){2}\d{4}$/; regex2 = /^\d{10}$/; regex3 = /^[1]\s(\d{3}\s){2}\d{4}|(\d{3}\s){2}\d{4}$/; regex4 = /^[1]\s[(]{1}\d{3}[)]{1}\d{3}[-]{1}\d{4}|[(]{1}\d{3}[)]{1}\d{3}[-]{1}\d{4}$/; regex5 = /^[1]\s[(]{1}\d{3}[)]{1}\s\d{3}[-]{1}\d{4}|[(]{1}\s\d{3}[)]{1}\d{3}[-]{1}\d{4}$/; if (regex1.test(str) || regex2.test(str) || regex3.test(str) || regex4.test(str) || regex5.test(str)) { return true; } else { return false; } } and 2 test doesn't pass correctly (both should come false true instead): telephonecheck("2(757)622-7382") , telephonecheck("(555-555-5555"). question how use | (or) operator (i think make code way nicer) , how describe expression within regex match specific character (e.g. "1" @ beginning of number)? did [1]{1} or [1]$ didn't seem work. hints , suggestions!
how describe expression within regex match specific character (e.g. "1" @ beginning of number)
to match specific character, use character. x valid regex string match letter "x". match special character, escape first. regex . match character; regex \. match period.
note regex x equivalent [x] in match same things, former shorter , easier read. when given choice, use single character directly (escaped if necessary!) , forget [ ].
your regex's contain expressions [-], [(], , [1]. drop brackets. on second one, need escape (.
expressions [(]{1} equivalent \(. {1} means match previous item once. using item accomplishes same thing. 2 characters lot shorter 6 , make regex easier read.
how use | (or) operator properly
using | operator simple enough. match on left, or on right side. enclose in parenthesis restrict match. example, a|bc match "a" or "bc". (a|b)c match "ac" , "bc".
Comments
Post a Comment