Pregunta sobre c#, regex – Declaración de expresiones regulares para solo números entre 0 y 255 en C #

1

¿Cómo escribo la declaración de expresiones regulares solo para números entre 0 y 255? 0 y 255 serán válidos para la declaración.

Sí, 001 es un valor válido. sanchop22
Es001 un valor valido? Fredrik Mörk

Tu respuesta

4   la respuesta
8

http://www.regular-expressions.info/numericranges.html

Tu ejemplo sería:

^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$ 
Esto acepta la cadena "-1" y no acepta "001" como 1. sanchop22
0

Tratar

([01]?\d\d?|2[0-4]\d|25[0-5])
Esto acepta la cadena "-1" y no acepta "001" como 1. sanchop22
4
^([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])$

Esta herramienta Es muy útil para tales cosas. Un poco de búsqueda tampoco hace daño a nadie.

Sin embargo, si desea permitir ceros iniciales, el patrón debe adaptarse. P.ej.:

^([01][0-9][0-9]|2[0-4][0-9]|25[0-5])$
Siento disentir. Joey
Esto acepta la cadena "-1" y no acepta "001" como 1. sanchop22
0

Intenta una mirada negativa detrás:

Explicación

<!--


Options: ^ and $ match at line breaks

Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind) «(?<!\-)»
   Match the character “-” literally «\-»
Assert position at a word boundary «\b»
Match the character “0” literally «0*»
   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 «([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])»
   Match either the regular expression below (attempting the next alternative only if this one fails) «[0-9]{1,2}»
      Match a single character in the range between “0” and “9” «[0-9]{1,2}»
         Between one and 2 times, as many times as possible, giving back as needed (greedy) «{1,2}»
   Or match regular expression number 2 below (attempting the next alternative only if this one fails) «1[0-9]{2}»
      Match the character “1” literally «1»
      Match a single character in the range between “0” and “9” «[0-9]{2}»
         Exactly 2 times «{2}»
   Or match regular expression number 3 below (attempting the next alternative only if this one fails) «2[0-4][0-9]»
      Match the character “2” literally «2»
      Match a single character in the range between “0” and “4” «[0-4]»
      Match a single character in the range between “0” and “9” «[0-9]»
   Or match regular expression number 4 below (the entire group fails if this one fails to match) «25[0-5]»
      Match the characters “25” literally «25»
      Match a single character in the range between “0” and “5” «[0-5]»
Assert position at a word boundary «\b»
-->

Preguntas relacionadas