I never understood how to make properly regex to divide my Strings.
I have this types of Strings example = "on[?a, ?b, ?c]";
Sometimes I have this, Strings example2 = "not clear[?c]";
For the first Example I would like to divide into this:
[on, a, b, c]
or
String name = "on";
String [] vars = [a,b,c];
And for the second example I would like to divide into this type:
[not clear, c]
or
String name = "not clear";
String [] vars = [c];
Thanks alot in advance guys 😉
If you know the character set of your identifiers, you can simply do a split on all of the text that isn’t in that set. For example, if your identifiers only consist of word characters (
[a-zA-Z_0-9]) you can use:If your identifiers only have A-Z (upper and lower) you could replace
\\Wabove with^A-Za-z.I feel that this is more elegant than using a complex regular expression.
Edit: I realize that this will have issues with your second example “not clear”. If you have no option of using something like an underscore instead of a space there, you could do one split on
[?(or substring) to get the “name”, and another split on the remainder, like so: