Achilles
Achilles

Reputation: 741

splitting strings by delimiter and other specific strings

I know how to split string by delimiters but I don't know how its done by a string. What I mean is I have a string such as

"(a AND b) OR c"

I want to split it so it ignores the brackets and the special words such as AND and OR. It should return me a string array of {a, b, c}

the same string could also be in the format such as "(a & b) || c"

I want to get the a,b,c into the string array and find their ID's and put their IDs into the initial string instead of them.

Upvotes: 1

Views: 246

Answers (1)

JamesSwift
JamesSwift

Reputation: 863

Here is a quick and dirty solution:

String str = "(a AND b) OR c"; // Any string you want
String delims = "AND|OR|NOT|[!&|()]+"; // Regular expression syntax
String newstr = str.replaceAll(delims, " ");
String[] tokens = newstr.trim().split("[ ]+"); // RE syntax again
// tokens == ["a", "b", "c"]

Note that the delims is a regular expression and you can add to it if you have more delimeters. This one is going to replace "AND", "OR", "NOT", and one or more of the characters "!", "&", "|", "(", or ")". It replaces each of these occurances with a space, then splits the string on spaces (making sure to trim the front and back so we don't get those in our array).

Let me know if you have any questions on this. Hope it helps.

Upvotes: 1

Related Questions