RegExp匹配任意字符串+8位数

时间:2016-05-12 23:14:14

标签: javascript regex

尝试以任意字符串+破折号+ 8位数字的格式匹配网址:

yellow-purse-65788544
big-yellow-purse-66784500
iphone-smart-case-water-resistant-55006610

我已经构建了这个,但它不起作用:

new RegExp(/^[a-z][A-Z]-\d{8}$/).test('big-yellow-purse-66784500'); // false

你能帮我修复破碎的RegExp吗?

4 个答案:

答案 0 :(得分:0)

  

字符串不是完全任意的。它将是小写的虚线字母数字。

您可以使用以下正则表达式,它排除了其他答案未考虑的误报列表(详见Regex101):

^(?:[a-z0-9]+-)+\d{8}$

<强> Regex101

示例构造:

&#13;
&#13;
document.body.textContent = /^(?:[a-z0-9]+-)+\d{8}$/.test('big-yellow-purse-66784500');
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:

/^([a-zA-Z]*-)+\d{8}$/.test("iphone-smart-case-water-resistant-55006610");

答案 2 :(得分:0)

你的字符串有几个破折号 - ),但正则表达式只有最后一个,试试这个:

/^[a-z-]+-\d{8}$/im

Regex101演示

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)

<强>演示:

&#13;
&#13;
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>"); 
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

如果字符串真的可以是任意的,你可以使用它:

/^.*?-\d{8}$/i

.+?是任意字符的非贪婪匹配,\d{8}表示匹配8位数字。

或者,您可以使用:

/^[\w-]+?-\d{8}$/i

这匹配任何数量的&#34;字&#34;或者&#39; - &#39;字符,然后是&#39; - &#39;和8位数。

这两者都与人类可读网址中常见的情况相符,其中有多个&#39; - &#39;顺序中的字符,可以通过转换类似&#34; Dollar $ ign money clip&#34;美元 - 点燃钱夹&#34;。

相关问题