Priyanshu Sharma
Priyanshu Sharma

Reputation: 123

How to split string on brackets ")("?

Input:

val str="(2500 - Analytical Charge Percentage of Monitoring Structure (MS) type Sub-Business Unit (SSBU) : 803.130000000000000000)(388 - Monitoring Structure (MS) type Sub-Business Unit (SSBU) : JzCddaxT)"

Would want two bigger strings inside () as elements of an array. In this case if we are splitting on ")(":

Expected Output:

arr(0) = "(2500 - Analytical Charge Percentage of Monitoring Structure (MS) type Sub-Business Unit (SSBU) : 803.130000000000000000"

arr(1) = "388 - Monitoring Structure (MS) type Sub-Business Unit (SSBU) : JzCddaxT)"

I am using str.split("[\\\\)\\\\(]") but its not working.

Upvotes: 0

Views: 887

Answers (1)

Andreas
Andreas

Reputation: 159086

split("[\\)\\(]")

will split on a ( and on a ), so this (abbreviated) text:

"(2500 (MS) Unit (SSBU) : 803.13)(388 (MS) Unit (SSBU) : JzCddaxT)"

becomes this:

["", "2500 ", "MS", " Unit ", "SSBU", " : 803.13", "", "388 ", "MS", " Unit ", "SSBU", " : JzCddaxT"]

which is obviously not what you want.

Since you seem to want to just split on the 2-character substring ")(", don't use a [ ] character class.

split("\\)\\(")

which will produce what you showed:

["(2500 (MS) Unit (SSBU) : 803.13", "388 (MS) Unit (SSBU) : JzCddaxT)"]

Upvotes: 7

Related Questions