navinpai
navinpai

Reputation: 995

Split String in Java with on previous character

I have a string, which is a chained process call, and I need to get the individual processes in a list, so that I can then work on the individual processes.

For eg.

if I have

'funca("hello world").funcb("this.is.sparta").funcc()'

I want to get an arraylist that has

['funca("hello world")' , 'funcb("this.is.sparta")' , 'funcc()']

Now, I cannot split the string on '.' as the parameters being passed can also have the '.' character. I tried splitting on ').' but this ends up with a ugly looking split of

['funca("hello world"' , 'funcb("this.is.sparta"' , 'funcc()']

So basically what I need now is a way to split on ').', but split only on the associated '.'. Is this possible with the split function? Or should I get locations of all ').' and then manually split?

I'm unsure how to proceed. Pointers much appreciated.

Upvotes: 2

Views: 209

Answers (2)

M A
M A

Reputation: 72854

You can use a positive lookbehind in your regex:

String text = "funca(\"hello world\").funcb(\"this.is.sparta\").funcc()";
String[] split = text.split("(?<=\\))\\.");
System.out.println(Arrays.toString(split));

Output:

[funca("hello world"), funcb("this.is.sparta"), funcc()]

The regex (?<=\))\. matches a dot preceded by a ).

Upvotes: 3

Rohit Jain
Rohit Jain

Reputation: 213243

You are not really splitting the string on some character, but are identifying a pattern in a large string. So, instead of using String#split(), you should use Matcher#find() to find all the patterns that matches func(arg1, arg2, ...). That pattern would be something like this:

\\w+\\([^)]*\\)

Code:

String str= "funca(\"hello world\").funcb(\"this.is.sparta\").funcc()";
Matcher matcher = Pattern.compile("\\w+\\([^)]*\\)").matcher(str);

List<String> matchedFunction = new ArrayList<String>();
while (matcher.find()) {
  matchedFunction.add(matcher.group());
}

System.out.println(matchedFunction);

Upvotes: 0

Related Questions