问题
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
回答1:
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
回答2:
Try with that regex:
^(?:\s|\R)*(?:-----BEGIN NEW CERTIFICATE REQUEST-----)(?<request>(?:.*\R)+)(?:-----END NEW CERTIFICATE REQUEST-----)(?:\s|\R)*$
Test it there
回答3:
While the RegEx check is useful, it would be better to actually try to decode the certificate.
Here is an example of doing that:
https://pkijs.org/examples/PKCS10_complex_example.html
来源:https://stackoverflow.com/questions/30322774/how-do-we-validate-the-format-of-the-csr-using-regex