文字列に含まれる数値が 20 以下で、数値のみを使用できる場合に true を返す正規表現が必要です。
4 に答える
次の番号と一致していると仮定します。
- 整数
- [0,20]の範囲内
これは機能するはずです:^(([01]?[0-9])|(20))$
。
フロートを一致させる場合、物事は少し厄介になります。数値範囲のチェックは、理想的には、常にプラットフォームの数値演算子を使用して実行する必要があります。
これは、20 以下の整数に一致します。
(?:\b|-)0*([0-9]|1[0-9]|20)\b
説明
(?: # Match the regular expression below
# Match either the regular expression below (attempting the next alternative only if this one fails)
\b # Assert position at a word boundary
| # Or match regular expression number 2 below (the entire group fails if this one fails to match)
- # Match the character “-” literally
)
0 # Match the character “0” literally
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
( # Match the regular expression below and capture its match into backreference number 1
# Match either the regular expression below (attempting the next alternative only if this one fails)
[0-9] # Match a single character in the range between “0” and “9”
| # Or match regular expression number 2 below (attempting the next alternative only if this one fails)
1 # Match the character “1” literally
[0-9] # Match a single character in the range between “0” and “9”
| # Or match regular expression number 3 below (the entire group fails if this one fails to match)
20 # Match the characters “20” literally
)
\b # Assert position at a word boundary
今後の課題についてはこちらをご覧ください。
正規表現をサポートする言語がわかりません。PCREのいくつかのバリアントを使用していると仮定します。
ここでのコードは、文字列に数値のみが含まれていることを厳密に検証するためのものです。
整数のみ、負ではないと仮定し、先行ゼロはありません:
^(1?\d|20)$
整数のみが、非負であると仮定して、任意の先行0を許可します。
^0*(1?\d|20)$
任意の整数、先行ゼロなし:
^(+?(1?\d|20)|-\d+)$
任意の整数、任意の先行0を許可します。
^(+?0*(1?\d|20)|-\d+)$
数値が任意に大きくない場合は、緩い正規表現で数値をキャプチャして\b[+-]?\d+(\.\d*)?\b
から、数値に変換して確認することをお勧めします。
(\b[0-9]\b|\b1[0-9]\b|\b20\b)
私のために働いた
整数のみ、負でないことを前提とし、先頭に 0 はありません
以前は 20 未満のパーセンテージを見つけていたので、最終的には次のようになります。
(\b[0-9]%|\b1[0-9]%|\b20%)