Jish Nair
Jish Nair

Reputation: 85

Scala split string regex pattern

I have a String that looks like this and I want to extract the bit between the pipe and the tilde.

{>}D003 S/N|555555~EB

So the result of the parsing should give me 555555 back. Here is what I tried, but without success:

"""\D003 S/N|.*\~""".r.findFirstIn("{>}D003 S/N|555555~EB")

which gives me:

Some({>}D003 S/N|555555~)

Upvotes: 2

Views: 788

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You may use a simple unanchored regex with a capturing group: D003 S/N\|([^~]+)~.

See the Scala demo:

val rx = """D003 S/N\|([^~]+)~""".r.unanchored
val s = "{>}D003 S/N|555555~EB"
val res = s match { 
    case rx(c) => c
    case _ => ""
}
println(res)

Pattern details:

  • D003 S/N\| - match a literal char sequence D003 S/N|
  • ([^~]+) - capturing group 1 matching 1 or more chars other than ~
  • ~ - a literal char ~.

Upvotes: 2

Related Questions