Shattered
Shattered

Reputation: 21

Splitting a string based on angle brackets?

Is there any way to split a string into sections based on angle brackets, so

1<2>3<4> should become ["1", "<2>", "3", "<4>"].

I've tried "1<2>3<4>".split("<([^>]*)>") but that only gives me ["1", "3"]

Upvotes: 0

Views: 793

Answers (3)

OneCricketeer
OneCricketeer

Reputation: 191983

Regex find on regular numbers, or those with brackets around them

scala> """\d+|(<\d+>)""".r.findAllIn("1<2>3<4>").toArray
res0: Array[String] = Array(1, <2>, 3, <4>)

Can also do """<?\d+>?""".r

Upvotes: 1

shmosel
shmosel

Reputation: 50756

You can use lookarounds to split before an open bracket or after a close bracket:

(?=<)|(?<=>)

Demo

Upvotes: 1

Andrey Tyukin
Andrey Tyukin

Reputation: 44967

With lookaheads:

scala> val s = "1<2>3<4>"
scala> s.split("(?=<)|(?<=>)")
res6: Array[String] = Array(1, <2>, 3, <4>)

See (?=X) and (?<=X) here.

Upvotes: 2

Related Questions