I am trying to get a substring in scala. The string that I have is the following:
fromTo: NT=xxx_bt_bsns_m,OD=ntis,OS=wnd,SX=xs,SZ=ddp,
fromTo: NT=xds_bt2_bswns_m,OD=nis,OS=wnd,SX=xs,SZ=ddp,
fromTo: NT=xxa_bt1_b1ns_m,OD=nts,OS=nd,SX=xs,SZ=ddp
I just want to get a substring with:
xxx_bt_bsns_m
Edit: This substring can be other, for example ddd_zn1_ldk
So what i have to try to get all the string that start with NT and ends with a "," maybe?
I am starting with scala so for this reason i am having doubts with this.
Thanks in advance!
CodePudding user response:
We could use a regex replacement here:
val input = "fromTo: NT=xxx_bt_bsns_m,OD=ntis,OS=wnd,SX=xs,SZ=ddp"
val output = input.replaceAll("^.*\\bNT=([^,] ).*$", "$1")
println(output) // xxx_bt_bsns_m
CodePudding user response:
Consider interpolated string patterns
input match {
case s"fromTo: NT=${nt},${_}" => nt
}
however this will throw an exception if it cannot pattern match the input, so you have to decide what to do in that case. Perhaps you could return empty string
input match {
case s"fromTo: NT=${nt},${_}" => nt
case _ => ""
}
or use an Option
to model the error case
input match {
case s"fromTo: NT=${nt},${_}" => Some(nt)
case _ => None
}