您字符串有幾個破折號(-),但正則表達式只是有最後一個,試試這個:
/^[a-z-]+-\d{8}$/im
Rege X101演示
https://regex101.com/r/rT7xT0/1
正則表達式的解釋:
/^[a-z-]+-\d{8}$/im
^assert position at start of a line
[a-z-]+ match a single character present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
a-z a single character in the range between a and z (case insensitive)
- the literal character -
- matches the character - literally
\d{8} match a digit [0-9]
Quantifier: {8} Exactly 8 times
$ assert position at end of a line
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
m modifier: multi-line. Causes^and $ to match the begin/end of each line (not only begin/end of string)
演示:
stringOne = "iphone-smart-case-water-resistant-55006610";
stringtwo = "big-yellow-purse-66784500";
stringThree = "iphone-smart-case-water-resistant-55006610222222";
var myregexp = /^[a-z-]+-\d{8}$/im;
if(myregexp.test(stringOne)){
document.write(stringOne + " - TRUE<br>");
}else{
document.write(stringOne + " - FALSE<br>");
}
if(myregexp.test(stringtwo)){
document.write(stringtwo + " - TRUE<br>");
}else{
document.write(stringtwo + " - FALSE<br>");
}
if(myregexp.test(stringThree)){
document.write(stringThree + " - TRUE<br>");
}else{
document.write(stringThree + " - FALSE<br>");
}
'-'需要'\'' – dandavis
@dandavis仍然無法使用。 new RegExp(/^[a-z] [A-Z] \ - \ d {8} $ /)。test('big-yellow-purse-66784500'); – ChrisRich
'/^[a-zA-Z \ - ] + - \ d {8} $ /',並且不會將它傳遞給RegExp(),不需要並且會打破東西 – dandavis