文字列が次の形式であるかどうかを示す正規表現が必要です。数字のグループはコンマで区切る必要があります。-で区切られた数値の範囲を含めることができます
300, 200-400, 1, 250-300
グループは任意の順序にすることができます。
これは私がこれまでに持っているものですが、文字列全体と一致していません。数字のグループにのみ一致します。
([0-9]{1,3}-?){1,2},?
文字列が次の形式であるかどうかを示す正規表現が必要です。数字のグループはコンマで区切る必要があります。-で区切られた数値の範囲を含めることができます
300, 200-400, 1, 250-300
グループは任意の順序にすることができます。
これは私がこれまでに持っているものですが、文字列全体と一致していません。数字のグループにのみ一致します。
([0-9]{1,3}-?){1,2},?
これを試してください:
^(?:\d{1,3}(?:-\d{1,3})?)(?:,\s*\d{1,3}(?:-\d{1,3})?|$)+
番号範囲を指定しなかったので、これはあなたにお任せします。いずれにせよ、正規表現で数学を行う必要があります:)
説明:
"
^ # Assert position at the beginning of the string
(?: # Match the regular expression below
\\d # Match a single digit 0..9
{1,3} # Between one and 3 times, as many times as possible, giving back as needed (greedy)
(?: # Match the regular expression below
- # Match the character “-” literally
\\d # Match a single digit 0..9
{1,3} # Between one and 3 times, as many times as possible, giving back as needed (greedy)
)? # Between zero and one times, as many times as possible, giving back as needed (greedy)
)
(?: # Match the regular expression below
# Match either the regular expression below (attempting the next alternative only if this one fails)
, # Match the character “,” literally
\\s # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\\d # Match a single digit 0..9
{1,3} # Between one and 3 times, as many times as possible, giving back as needed (greedy)
(?: # Match the regular expression below
- # Match the character “-” literally
\\d # Match a single digit 0..9
{1,3} # Between one and 3 times, as many times as possible, giving back as needed (greedy)
)? # Between zero and one times, as many times as possible, giving back as needed (greedy)
| # Or match regular expression number 2 below (the entire group fails if this one fails to match)
\$ # Assert position at the end of the string (or before the line break at the end of the string, if any)
)+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
"
^(\d+(-\d+)?)(,\s*(\d+(-\d+)?))*$
これは機能するはずです:
/^([0-9]{1,3}(-[0-9]{1,3})?)(,\s?([0-9]{1,3}(-[0-9]{1,3})?))*$/
繰り返しが必要です:
(?:([0-9]{1,3}-?){1,2},?)+
数字が正しいことを確認するために、つまり010のような数字と一致しないようにするために、正規表現を少し変更することをお勧めします。また、正規表現の範囲部分を変更して、100-200-のように一致せず、100または100-200のみに一致させ、コンマの後に空白のサポートを追加しました(オプション)。
(?:(([1-9]{1}[0-9]{0,2})(-[1-9]{1}[0-9]{0,2})?){1,2},?\s*)+
()
また、キャプチャする対象によっては、キャプチャブラケットを非キャプチャブラケットに変更することもできます。(?:)
アップデート
最新のコメントに基づく改訂版:
^\s*(?:(([1-9][0-9]{0,2})(-[1-9][0-9]{0,2})?)(?:,\s*|$))+$
([0-9-]+),\s([0-9-]+),\s([0-9-]+),\s([0-9-]+)
この正規表現を試してください
^(([0-9]{1,3}-?){1,2},?\s*)+$