Estoy tratando de obtener solo los encabezados h1 y h2 del archivo de descuento usando expresiones regulares, pero desafortunadamente no conozco bien las expresiones regulares y no puedo escribir la solución correcta.
Con esta expresión estoy cerca de la solución (creo que sí): /\#{1,2} (.*?)(\\r\\n|\\r|\\n)/gm
Pero también devuelve encabezados con más de dos hashes.
Caso de prueba:
# first \r ## second \r ### third \r## fourth \r Esto debería devolver ['first', 'second', 'fourth']
Usar
/(?<!#)#{1,2} (.*?)(\\r(?:\\n)?|\\n)/gmVer prueba de expresiones regulares .
EXPLICACIÓN
-------------------------------------------------------------------------------- (?<! look behind to see if there is not: -------------------------------------------------------------------------------- # '#' -------------------------------------------------------------------------------- ) end of look-behind -------------------------------------------------------------------------------- #{1,2} '#' (between 1 and 2 times (matching the most amount possible)) -------------------------------------------------------------------------------- ' ' -------------------------------------------------------------------------------- ( group and capture to \1: -------------------------------------------------------------------------------- .*? any character except \n (0 or more times (matching the least amount possible)) -------------------------------------------------------------------------------- ) end of \1 -------------------------------------------------------------------------------- ( group and capture to \2: -------------------------------------------------------------------------------- \\ '\' -------------------------------------------------------------------------------- r 'r' -------------------------------------------------------------------------------- (?: group, but do not capture (optional (matching the most amount possible)): -------------------------------------------------------------------------------- \\ '\' -------------------------------------------------------------------------------- n 'n' -------------------------------------------------------------------------------- )? end of grouping -------------------------------------------------------------------------------- | OR -------------------------------------------------------------------------------- \\ '\' -------------------------------------------------------------------------------- n 'n' -------------------------------------------------------------------------------- ) end of \2