Java Regex .split String of CFGs

Viewed 25

Been having problems parsing a line String from a CFG file,

the input string is:

String str = "The <animal> loves to <activity>.";

I've tried to use split with regex to split by the Non-terminals (<*>), however it's not producing the desired results:

What I've tried:

str.split("(?=<)");

Output:

"The ", "<animal> loves to", "<activity>."

Desired output:

"The ", "<animal>", " loves to ", "<activity>", "." 
1 Answers

You may split using lookarounds:

String str = "The <animal> loves to <activity>.";
String[] parts = str.split("(?=<)|(?<=>)");
System.out.println(Arrays.toString(parts));

This prints:

[The , <animal>,  loves to , <activity>, .]

The splitting logic used above says to split at any point in the string when > immediately precedes or when < immediately follows.

Related