我有一个如下字符串:
val prefix= "PREFIX[EB.AR.]"
我想从该字符串中获取值EB.AR.
。
任何人都请指导我该怎么做?
答案 0 :(得分:3)
// The escaped braces ('\[ ... \]') are for matching the literal characters.
// The parenthesis ('(...)') are for making a capturing group.
// The non-escaped braces ('[...]') are for making an or.
// The '+' means 1 or more times.
// The '\w' means any word character.
// The escaped dot ('\.') is for matching the literal character.
val prefix = raw"PREFIX\[([\w\.]+)\]".r
// extracts what is inside the capturing group.
def extract(text: String): String = text match { case prefix(inside) => inside }
extract("PREFIX[EB.AR.]")
// res0: String = EB.AR.
有关模式的更多信息,请阅读javadoc
答案 1 :(得分:2)
val prefix= "PREFIX[EB.AR.]"
val RE = raw"\[([^\]]*)\]".r.unanchored //capture everything inside the 1st []
val RE(extractedStr) = prefix //will throw if no []
//extractedStr: String = EB.AR.