expresión regular para que coincida exactamente con 5 dígitos


testing= testing.match(/(\d{5})/g);

Estoy leyendo un html completo en variable. De la variable, desea agarrar todos los números con el patrón de exactamente 5 dígitos. No hay necesidad de preocuparse de si antes / después de este dígito tiene otro tipo de palabras. Solo quiero asegurarme de que lo que sea que sean números de 5 dígitos han sido sacados.

Sin embargo, cuando lo aplico, no solo saca el número con exactamente 5 dígitos, el número con más de 5 dígitos también se recupera...

Había intentado poner ^ delante y $ detrás, pero lo que hace que el resultado salga como nulo.

Author: i need help, 2011-02-12

5 answers

Estoy leyendo un archivo de texto y quiero usar expresiones regulares a continuación para extraer números con exactamente 5 dígitos, ignorando alfabetos.

Prueba esto...

var str = 'f 34 545 323 12345 54321 123456',
    matches = str.match(/\b\d{5}\b/g);

console.log(matches); // ["12345", "54321"]

JsFiddle .

La palabra límite \b es tu amigo aquí.

Actualizar

Mi expresión regular obtendrá un número como este 12345, pero no como a12345. Las otras respuestas proporcionan grandes expresiones regulares si usted requiere el último.

 43
Author: alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-12 01:44:43

Mi cadena de prueba para lo siguiente:

testing='12345,abc,123,54321,ab15234,123456,52341';

Si entiendo tu pregunta, querrías ["12345", "54321", "15234", "52341"].

Si los motores JS soportaban lookbehinds regexp, podrías hacer:

testing.match(/(?<^|\D)\d{5}(?=\D|$)/g)

Dado que actualmente no lo hace, usted podría:

testing.match(/(?:^|\D)(\d{5})(?=\D|$)/g)

Y eliminar el primer dígito de los resultados apropiados, o:

pentadigit=/(?:^|\D)(\d{5})(?=\D|$)/g;
result = [];
while (( match = pentadigit.exec(testing) )) {
    result.push(match[1]);
}

Tenga en cuenta que para IE, parece que necesita usar una RegExp almacenada en una variable en lugar de una regexp literal en el bucle while, de lo contrario obtendrá un infinito bucle.

 5
Author: outis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:39

Esto debería funcionar:

<script type="text/javascript">
var testing='this is d23553 test 32533\n31203 not 333';
var r = new RegExp(/(?:^|[^\d])(\d{5})(?:$|[^\d])/mg);
var matches = [];
while ((match = r.exec(testing))) matches.push(match[1]);
alert('Found: '+matches.join(', '));
</script>
 2
Author: Mark Eirich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-12 01:33:31

¿Qué tiene esto? \D(\d{5})\D

Esto hará en:

F 23 23453 234 2344 2534 hallo33333 "50000"

23453, 33333 50000

 1
Author: Luke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-12 01:36:26

No hay necesidad de preocuparse de si antes/después de este dígito tiene otro tipo de palabras

Para que coincida con el patrón de 5 dígitos en cualquier parte de la cadena, sin importar si está separada por espacio o no, use esta expresión regular (?<!\d)\d{5}(?!\d).

Ejemplos de códigos JavaScript:

var regexp = new RegExp(/(?<!\d)\d{5}(?!\d)/g); 
    var matches = yourstring.match(regexp);
    if (matches && matches.length > 0) {
        for (var i = 0, len = matches.length; i < len; i++) {
            // ... ydo something with matches[i] ...
        } 
    }

Aquí hay algunos resultados rápidos.

  • Abc12345xyz (✓)

  • 12345abcd (✓)

  • Abcd12345 (✓)

  • 0000aaa2 (✖)

  • A1234a5 (✖)

  • 12345 (✓)

  • <space>12345<space>12345 (✓✓)

 0
Author: Muhammad Saqib,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-15 21:44:23