I'm currently trying to validate a CSRformat via javascript regex and I'm currently stuck with this regex:
^ (-----BEGIN NEW CERTIFICATE REQUEST-----)(.*[\r\ n]) + (-----END NEW CERTIFICATE REQUEST-----) $
What I want to accomplish is that I need to validate only the 1st occurence of the
-----BEGIN NEW CERTIFICATE REQUEST-----
and
-----END NEW CERTIFICATE REQUEST-----
so anything below except white spaces or enter spaces becomes invalid.
This must be invalid as well:
-----BEGIN NEW CERTIFICATE REQUEST-----
test
test
test
test
-----END NEW CERTIFICATE REQUEST-----
-----BEGIN NEW CERTIFICATE REQUEST-----
test
test
test
test
-----END NEW CERTIFICATE REQUEST-----
it should only be:
-----BEGIN NEW CERTIFICATE REQUEST-----
test
test
test
test
-----END NEW CERTIFICATE REQUEST-----
Looks like I'm getting a hard time as well to figure this out via RegEx
You can use this version of regex that will capture only the first START/END block only in case it is a unique block of this kind:
^(?:(?!-{3,}(?:BEGIN|END) NEW CERTIFICATE REQUEST)[\s\S])*(-{3,}BEGIN NEW CERTIFICATE REQUEST(?:(?!-{3,}END NEW CERTIFICATE REQUEST)[\s\S])*?-{3,}END NEW CERTIFICATE REQUEST-{3,})(?![\s\S]*?-{3,}BEGIN NEW CERTIFICATE REQUEST[\s\S]+?-{3,}END NEW CERTIFICATE REQUEST[\s\S]*?$)
See demo
EDIT:
To make sure we just match at the end, with optional spaces, you can use a shorter regex:
^(?:(?!-{3,}(?:BEGIN|END) NEW CERTIFICATE REQUEST)[\s\S])*(-{3,}BEGIN NEW CERTIFICATE REQUEST(?:(?!-{3,}BEGIN NEW CERTIFICATE REQUEST)[\s\S])*?-{3,}END NEW CERTIFICATE REQUEST-{3,})\s*$
See Demo 2