簡體   English   中英

正則表達式 - 驗證逗號分隔的數字列表,長度為 1 到 3 位

[英]Regex - validating comma-separated list of numbers, 1 to 3 digits long

我正在嘗試驗證以逗號分隔的數字列表,其中數字可以是 1 到 3 位數字,可以以 0 開頭但不能為 0(0、00 或 000)。 我在下面使用,但是當我測試 '44,222,555' 時,我變得無效:

^([1-9]|[0-9][1-9]|[0-9][0-9][1-9](?:,(?:[1-9]|[0-9][1-9]|[0-9][0-9][1-9]))*)$

我認為 90 在這里也無效,但應該有效

您可以使用負前瞻來簡化您的正則表達式:

/^(?!0+\b)[0-9]{1,3}(?:,(?!0+\b)[0-9]{1,3})*$/gm

正則表達式演示

(?!0+\\b)是負前瞻,如果我們在當前位置之前的單詞邊界之前有一個或多個零,則匹配失敗。

在這種情況下

注意:根據字符串的大小,不使用全局標志會提高速度。

  • 每組允許一到三個號碼
  • 允許一對多組
  • 不允許 0, 00, 000 基於零的組合
  • 允許 01、010、001、100 個基於零的組合
  • 如果有多於一組數字,則在組之間用逗號分隔
  • 不允許以逗號結尾

 let regex = new RegExp('^((?!0+\\\\b)[0-9]{1,3}\\,?\\\\b)+$'); // NOTE: If using literal notation /regex/.test() then "\\" is not escaped. // ie '^((?!0+\\\\b)[0-9]{1,3}\\,?\\\\b)+$' becomes /^((?!0+\\b)[0-9]{1,3}\\,?\\b)+$/ // /^((?!0+\\b)[0-9]{1,3}\\,?\\b)+$/.test(string); console.log('Passes question test: 44,222,555 ', regex.test('44,222,555')); console.log('Passes question test: 90 ', regex.test('90')); console.log('Can contain multiple sets of one to three numbers: ', regex.test('1,22,333')); console.log('Cannot have more than three numbers in a set 1234', !regex.test('1234')); console.log('Can have one number in a set ', regex.test('1')); console.log('Cannot have 0 alone as a set: ', !regex.test('0')); console.log('Cannot have 00 alone as a set: ', !regex.test('00')); console.log('Cannot have 000 alone as a set: ', !regex.test('000')); console.log('Cannot end in a comma ', !regex.test('123,')); console.log('Cannot contain multiple commas next to each other ', !regex.test('123,,694')); console.log('Allowed zero combinations are 00#, #00, 0#0, 00#, ##0, 0## ', regex.test('001,100,010,001,110,011')); console.log('Cannot be just a comma ', !regex.test(',')); console.log('Cannot be a blank string ', !regex.test(''));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM