我使用以下正則運算式來捕獲 10 個數字和字母:
/[a-zA-Z0-9]{10}/g
如果 10 個字符只是數字和字母,則效果很好。
例如輸入:
12345xcdw034342
它捕獲12345xcdw0
但是在這種帶有特殊字符或空格的情況下,它不會捕捉到它。
123}456712234324Zz3或者123}45 71223AB3
它應該捕獲 10 個數字和字母方面的字符。
任何幫助將不勝感激。
uj5u.com熱心網友回復:
你可以做到,但不能沒有任何額外的處理
由于您沒有具體說明您使用的是哪種語言,我將使用 Javascript,因為它非常通用,但相同的邏輯必須適用于任何語言。
以下是我能想到的選項
如果我有 testString = "12@34{56A789BDE"
- 匹配所有直到前十個字母數字字符,然后洗掉結果字串中的特殊字符
testString.match(/(\w.*?){10}/)[0].replaceAll(/\W/g, '')
// results '123456A789'
// explanation: we take the first \w and use .*? to indicate that we dont care if the alphanumeric has a non-alphanumeric right next to it, then we clean the result by removing \W which means non-alphanumeric
- 只匹配前十個字母數字字符,然后將它們連接起來形成一個結果字串
testString.match(/\w/g).splice(0,10).join('')
// results '123456A789'
// explanation: we match 10 groups of aphanumeric characters represented by \w (note the lowercase) and we join the first 10 (using splice to get them) as each group "()" is in the case of javascript returned as an element of an array of matches
- 從字串中洗掉特殊字符,然后取前十個
testString.replaceAll(/\W/g,'').match(/\w{10}/)[0]
// results '123456A789'
// explanation: we replace \W which means non alpha numeric characters, with '' to delete them then we match the first ten
uj5u.com熱心網友回復:
您可以使用
/[a-zA-Z0-9](?:[^a-zA-Z0-9]*[a-zA-Z0-9]){9}/g
請參閱正則運算式演示。詳情:
[a-zA-Z0-9]- 一個字母數字(?:[^a-zA-Z0-9]*[a-zA-Z0-9]){9}- 除字母數字字符和字母數字字符之外的任何零個或多個字符出現九次。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/389368.html
