簡體   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