JohnBigs JohnBigs - 8 months ago 62
Scala Question

How to detect if a string have letters in the beginning using scala funcs or regex?

I have a string number that might and might not have 2 or more chars in the beginning of the number, and maybe some chars that are not letters or numbers.

If its two or more in the beginning so delete the first 2 and clean the string from chars others than letters or numberss.

I want to detect that either using scala funcs or regex and clean this string.


"ABC12345" (after function) => "C12345"

"AB12345" (after function) => "12345"

"A12345" (after function) => "A12345"

"ABC1 23 +.4 5" (after function) => "C12345"

Answer Source

Regex matching characters which you want to remove:


It matches either exactly two letters at the beginning of string or anything other than [A-Z0-9].

Usage in Scala:

scala> val regex = """^[A-Z]{2}|[^A-Z0-9]""".r
regex: scala.util.matching.Regex = ^[A-Z]{2}|[^A-Z0-9]

scala> val ss = List("ABC12345", "A12345", "ABC1 23 +.4 5")
ss: List[String] = List(ABC12345, A12345, ABC1 23 +.4 5)

scala> => regex.replaceAllIn(s, ""))
res0: List[String] = List(C12345, A12345, C12345)