C# extract text file block
I need to extract Public key block from a file. The file looks like this:
.. some more data here ..
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v2.0.17 (MingW32)
Stmjb2vAyoFAt5EbfNLEPCrwIDt7gB6cS2kldF7nechuNoyEzevJQMfQ8uJChR9g
h/eUqqzE/cqCLHEruLMR38NCVYTEuCvTjOCtAnU9BCyX1Ir11aDUe0A4drcNISrv
pEYjbNh4pb5sZbxKfMrx7PPUOsLH/vpMZFy/ABEBAAG0JEVsa2FydF90ZXN0XzIw
MTEgPHN1cHBvcnRAZWxrYXJ0LnBsPokBOAQTAQIAIgUCTjaYUQIbAwYLCQgHAwIG
...
-----END PGP PUBLIC KEY BLOCK-----
.. some more data here ..
Before and afther that key block there is mo开发者_如何学Pythonre info. Heres what i tried:
static bool GetPublicKey(Stream keyI)
{
StreamReader reader = new StreamReader(keyI);
string key = reader.ReadToEnd();
Regex r = new Regex("(-----BEGIN PGP PUBLIC KEY BLOCK-----\\r\\n(.*?)-----END PGP PUBLIC KEY BLOCK-----\\r\\n)");
Match m = r.Match(key);
if (m.Success)
return true;
}
But i couldnt get it working..
How could i do this with using regex?
I think this is simplest:
var regex = new Regex(
"-----BEGIN PGP PUBLIC KEY BLOCK-----(.*?)-----END PGP PUBLIC KEY BLOCK-----",
RegexOptions.Singleline);
I don't understand what you mean by (.*?)
. Shouldn't it just be .*
- match any character, any number of times? Also try taking out the \\r\\n
. I can't see anything else wrong with the regex.
Use the following regular expression:
-----BEGIN PGP PUBLIC KEY BLOCK-----.*([a-zA-Z0-9/]+).*-----END PGP PUBLIC KEY BLOCK-----
Take the first group and you should have your key !
If the PGP key contains other characters, please be sure to add them. I'm not familiar with the character range myself, so I've taken what you've posted and put it in there.
精彩评论