我正在處理正則運算式的問題。我有一個 maxLength 10 的輸入。
到目前為止,我已經實作了第一個給定值可以是數字,例如 12345,但是它等待一個破折號,然后你可以寫一個字母或再次輸入一個數字 maxLength=10,例如:12345-a121 是允許的,它適用于當前
但我希望在 5 位數字之后允許字母或破折號,因為目前使用這個正則運算式,它只允許在 5 位數字之后破折號。例如 12345a 或 12345- 是允許的。這是我正在使用的實際正則運算式。
Valid/Matches: 12345a235, 123a, 12345-aa1, 12345a, 12345-a.
Not Valid/Does not matches: -11, 111111, aaaa,
(?=^[^W_]{1,5}-[^W_]{1,8}$)^.{1,10}$|^[^W_]{1,5}$
我正在 regex101.com 上進行除錯,但我沒有找到允許的方法。例如 12345a
這是檢查它是否匹配的條件。
if (!this.value.toString().match('^\d{1,5}(?!\d )[-\p{L}\d] $') && this.value.toString()) {
return ValidationInfo.errorCode("You need to do something");
感謝您的幫助
uj5u.com熱心網友回復:
編輯,因為第一種方法的模式可以簡化,并且也缺少結束序列長度的限制。
Letter僅與unicode 屬性轉義匹配/^\d{1,5}[-\p{L}][-\p{L}\d]{0,9}$/u
Letter使用unicode 屬性轉義匹配和捕獲/^(?<digitsOnly>\p{N}{1,5})(?<miscellaneous>[-\p{L}][-\p{L}\p{N}]{0,9})$/u
示例代碼...
const multilineSample = `12345a235
123a
12345-aa1
12345a
12345-a
12-a235dkfsf
12-a235dkfsfs
123a-dssava-y
123a-dssava-1a
12345-aa1--asd-
12345-aa1--asd-s
-11
111111
aaaa`;
// see ... [https://regex101.com/r/zPkcwv/3]
const regXJustMatch = /^\d{1,5}[-\p{L}][-\p{L}\d]{0,9}$/gmu;
// see ... [https://regex101.com/r/zPkcwv/4]
const regXNamedGroups =
/^(?<digitsOnly>\p{N}{1,5})(?<miscellaneous>[-\p{L}][-\p{L}\p{N}]{0,9})$/gmu;
console.log(
'matches only ...',
multilineSample.match(regXJustMatch)
);
console.log(
'matches and captures ...', [
...multilineSample.matchAll(regXNamedGroups)
]
.map(({ 0: match, groups }) => ({ match, ...groups }))
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
第一種方法
簡單明了...
/^\d{1,5}(?!\d )[-\p{L}\d] $/u使用命名的捕獲組...
/^(?<digitsOnly>\p{N}{1,5}(?!\p{N} ))(?<miscellaneous>[-\p{L}\p{N}] )$/u
對于這兩種變體,很明顯從...開始
- 至少 1 到 5 位的數字序列...
- 傳統的 ...
^\d{1,5} - unicode 屬性轉義...
^\p{N}{1,5}
- 傳統的 ...
也很清楚,一個人想要以任何破折號和/或單詞的字符序列結尾。由于必須排除,_因此不能只\w對字母和數字使用轉義符,因為也\w包含/包含_。但是可以使用unicode 屬性轉義,因此...
- 覆寫具有有效字符類的行尾的正則運算式是...
- 已經混...
[-\p{L}\d] $ - 主要是 unicode 轉義...
[-\p{L}\p{N}] )$
- 已經混...
像 ... /^\d{1,5}[-\p{L}\d] $/u... 這樣的組合正則運算式幾乎涵蓋了要求,但111111即使它不應該符合要求,也無法匹配哪個原因。
一個負前瞻......(?!\d )分別(?!\p{N} )......在起始數字序列之后確實會阻止任何其他(終止)僅數字序列,因此123456不再匹配。
示例代碼...
const multilineSample = `12345a235
123a
12345-aa1
12345a
12345-a
-11
111111
aaaa`;
// see ... [https://regex101.com/r/zPkcwv/1]
const regXJustMatch = /^\d{1,5}(?!\d )[-\p{L}\d] $/gmu;
// see ... [https://regex101.com/r/zPkcwv/2]
const regXNamedGroups =
/^(?<digitsOnly>\p{N}{1,5}(?!\p{N} ))(?<miscellaneous>[-\p{L}\p{N}] )$/gmu;
console.log(
'matches only ...',
multilineSample.match(regXJustMatch)
);
console.log(
'matches and captures ...', [
...multilineSample.matchAll(regXNamedGroups)
]
.map(({ 0: match, groups }) => ({ match, ...groups }))
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/433047.html
標籤:javascript 有角度的 打字稿
