Home > Blockchain >  Scala case class string pattern matching not working as expected?
Scala case class string pattern matching not working as expected?

Time:10-26

I am using scala 2.13 and have a string like this:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAtp/Uo28kOjROL50aajnpK25CJoVoic2bqqu6OS2baWWD9fT2
ESqq8mbFxYN3O7JXbs 74YpTdg1jSUALOz9zj/H2eCF71QYvoHmdoi0iiQuy3gS1
6YczVvBvinSwfEnO6Wi/Xx6AC8urdr==
-----END RSA PRIVATE KEY-----

and I want to extract out

MIIEpAIBAAKCAQEAtp/Uo28kOjROL50aajnpK25CJoVoic2bqqu6OS2baWWD9fT2
ESqq8mbFxYN3O7JXbs 74YpTdg1jSUALOz9zj/H2eCF71QYvoHmdoi0iiQuy3gS1
6YczVvBvinSwfEnO6Wi/Xx6AC8urdr==

I am using it as follows:

val privateKey =
  "-----BEGIN RSA PRIVATE KEY-----\r\nMIIEpAIBAAKCAQEAtp/Uo28kOjROL50aajnpK25CJoVoic2bqqu6OS2baWWD9fT2ESqq8mbFxYN3O7JXbs 74YpTdg1jSUALOz9zj/H2eCF71QYvoHmdoi0iiQuy3gS16YczVvBvinSwfEnO6Wi/Xx6AC8urdr==\r\n-----END RSA PRIVATE KEY-----\r\n"

val result = privateKey match {
  case s"-----BEGIN RSA PRIVATE KEY-----\r\n$privateKeyB64\r\n-----END RSA PRIVATE KEY-----\r\n" => privateKeyB64
  case _ => {
    throw AEMServiceAccountError(s"Invalid RSA Private Key - Please check service account credentials for AEM.")
  }
}
println(result)

but the above code always throws Invalid RSA Private Key - Please check service account credentials for AEM.

Can someone help me debug what am I doing wrong here?

CodePudding user response:

Perhaps reason is in call unapply in pattern matching Works with regex

val regex = "-----BEGIN RSA PRIVATE KEY-----\r\n(.*)\r\n-----END RSA PRIVATE KEY-----\r\n".r
val result = privateKey match {
  case regex(privateKeyB64) => privateKeyB64
  case _ => throw AEMServiceAccountError(s"Invalid RSA Private Key - Please check service account credentials for AEM.")
}

CodePudding user response:

Extracting the variable outside solves the issue. Not sure why it doesn't work inlined.

val expectedPrivateKey = s"-----BEGIN RSA PRIVATE KEY-----\r\n$privateKeyB64\r\n-----END RSA PRIVATE KEY-----\r\n"

val result = privateKey match {
  case `expectedPrivateKey` => privateKeyB64
  case _ => {
    throw AEMServiceAccountError(s"Invalid RSA Private Key - Please check service account credentials for AEM.")
  }
}
  • Related