I have an exeption in a regex. With this regex
https://regex101.com/r/pxTfci/1
I can match all data (key:value) from a string separate by ,
. Problem I have a conflict with some List who is formatted like that
Mylist:[data1, data2, data3]
With this regex (?<=(?<!: *)\[).*?(?=, )|(?<=, (?=[^ \r\n]))(?:.*?(?=, )|[^\r\n\[\]] ?(?=\])|[^\r\n] \](?= *\]))
I have 3 match
match 1 = Mylist:[data1
match 2 = data2
match 3 = data3]
I search for this exeption, when I have [
]
, to have in output Mylist:[data1, data2, data3]
I don't know if it's possible. here is an exemple of complet input format
MyString=[XXXXXX:XX XX XX XX, XXXXX:332.83, XXXXX:XXX-XX-XX XX:XX:XX, XXXX:0.0, XXXX:2, XXXX:0, XXXX:-256, XXXX:5, XXXX:136935, XXXX:0, XXXX:XX XXX XXX, XXXX:0.5, XXXXX:true, XXXX:0.509375, XXX:0.0, 2022-09-17,XXXXX:1, list1:[2000-00-00 00:00, 2022-11-16 15:29, 2022-11-16 15:29], list2:[2000-00-00 00:00, 2022-11-16 15:29, 2022-11-16 15:29], ]
I search to have
match 1 = XXXXXX:XX XX XX XX
match 2 = XXXXX:332.83
...
match x =2022-09-17,XXXXX:1
match y =list1:[2000-00-00 00:00, 2022-11-16 15:29, 2022-11-16 15:29]
match z =list2:[2000-00-00 00:00, 2022-11-16 15:29, 2022-11-16 15:29]
CodePudding user response:
You have two options:
Firstly try something like this :
List<String> listString = [];
String MyString =
"[XXXXXX:XX XX XX XX, XXXXX:332.83, XXXXX:XXX-XX-XX XX:XX:XX, XXXX:0.0, XXXX:2, XXXX:0, XXXX:-256, XXXX:5, XXXX:136935, XXXX:0, XXXX:XX XXX XXX, XXXX:0.5, XXXXX:true, XXXX:0.509375, XXX:0.0, 2022-09-17,XXXXX:1, list1:[2000-00-00 00:00, 2022-11-16 15:29, 2022-11-16 15:29], list2:[2000-00-00 00:00, 2022-11-16 15:29, 2022-11-16 15:29], ]";
String newString = MyString.substring(1, MyString.length - 1);
bool save = true;
int start = 0;
for (int i = 0; i < newString.length; i ) {
if (newString[i] == "," && save) {
listeString.add(newString.substring(start, i));
start = i 1;
} else if (newString[i] == "[") {
save = false;
} else if (newString[i] == "]") {
save = true;
}
}
or
When you create your string, you replace your "," in your lists with a special character that you can easily change.
Have a good day