0

I don't know much about regex. So can you please tell me how to split the below string to get the desired output?

String ruleString= "/Rule/Account/Attribute[N='accountCategory' and V>=1]"+
                " and /Rule/Account/Attribute[N='accountType' and V>=34]"+
                  " and /Rule/Account/Attribute[N='acctSegId' and V>=341]"+
                   " and /Rule/Account/Attribute[N='is1sa' and V>=1]"+
                    " and /Rule/Account/Attribute[N='isActivated' and V>=0]"+
                    " and /Rule/Account/Attribute[N='mogId' and V>=3]"+
                    " and /Rule/Account/Attribute[N='regulatoryId' and V>=4]"+
                    " and /Rule/Account/Attribute[N='vipCode' and V>=5]"+
                    " and /Rule/Subscriber/Attribute[N='agentId' and V='346']​";

Desired output:

a[0] = /Rule/Account/Attribute[N='accountCategory' and V>=1]

a[1] = /Rule/Account/Attribute[N='accountType' and V>=34]
.
.
.

a[n] = /Rule/Subscriber/Attribute[N='agentId' and V='346']

We can not simply split a string using " and " as we have two of those in the string (one is required and other one is not)

I want to split it something like this

String[] splitArray= ruleString.split("] and ");

But this won't work, as it will remove the end bracket ] from each of the splits.

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
Bhuvan
  • 2,209
  • 11
  • 33
  • 46

2 Answers2

2

Split your input according to the below regex.

String[] splitArray= ruleString.split("\\s+and\\s+(?=/)");

This splits the input according to the and which exits just before to the forward slash.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Hi.. Can you add another regex in this answer to split the string according to this pattern? --> ] and / – Bhuvan Mar 19 '15 at 14:36
  • ok.. got it.. I think its this --> ruleString.split("(?<=\\])\\s*and\\s*(?=/)"); – Bhuvan Mar 19 '15 at 14:37
2

You have to use look-behind here:

String[] splitArray= ruleString.split("(?<=\\])\\s*and\\s*");
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525