繁体   English   中英

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

[英]RegExp match arbitrary string + 8 digits

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

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 吗?

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

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

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

正则表达式101

示例构造:

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

尝试这个:

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

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

/^[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)

演示:

 stringOne = "iphone-smart-case-water-resistant-55006610"; stringtwo = "big-yellow-purse-66784500"; stringThree = "iphone-smart-case-water-resistant-55006610222222"; var myregexp = /^[az-]+-\\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>"); }

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

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

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

或者,您可以使用:

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

这匹配任意数量的“单词”或“-”字符,后跟“-”和 8 位数字。

这两者也与人类可读的 URL 中常见的情况相匹配,其中顺序有多个“-”字符,这可以通过将诸如“Dollar $ign money clip”之类的内容转换为“dollar--ign-money clip”来实现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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